zoukankan      html  css  js  c++  java
  • 一个异步队列

    。。。想了想还是写下来

    一道题: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。。。


    过去了就过去了

    就像没发生过

  • 相关阅读:
    5. Longest Palindromic Substring
    24. Swap Nodes in Pairs
    23. Merge k Sorted Lists
    22. Generate Parentheses
    21. Merge Two Sorted Lists
    20. Valid Parentheses
    19. Remove Nth Node From End of List
    18. 4Sum
    17. Letter Combinations of a Phone Number
    14. Longest Common Prefix
  • 原文地址:https://www.cnblogs.com/zqiong/p/6629599.html
Copyright © 2011-2022 走看看