。。。想了想还是写下来
一道题:laz().say('something').sleep(1000).eat('dinner')//输出something,过1000ms,输出awake after 1000ms,然后输出dinner
就是这种链式调用,并且前面的异步的执行完才执行后面的
贴代码
function Laz(){ this.queue = []//搞个队列 var self = this this.next = function () { if(this.queue.length > 0) { self.queue.shift()() } } setTimeout(function(){ self.next() }, 0)//在下一个event loop启动 this.say = function(words) { this.queue.push(function(){ console.log(words) self.next() }) return this//每个都要返回this }, this.sleep = function(time) { this.queue.push(function(){ setTimeout(function(){ console.log('awake after ' + time +'ms') self.next() }, time) }) return this }, this.eat = function(meal) { this.queue.push(function(){ console.log('eat' + meal) self.next() }) return this } } function laz(){return new Laz()}
效果
回头搞个promise。。。
过去了就过去了
就像没发生过