JavaScript框架设计-异步处理

setTimeout和setInterval


Mochikit Deferred


JSDeferred

jQuery Deferred


Promise/A 与 mmDeferred


javascript 异步处理的前景


最简单的一个案例

实现思路:通过一个变量和一个数组来实现,变量表示是否有方法正在执行,然后用数组组织需要异步处理的方法,

通过每个调用方法调用success 来实现后续方法的调用。

function ExecuteQueue(){
    this.queue = [];
    this.executing = false;
}

ExecuteQueue.prototype = {
    then:function(foo){
        if(this.executing){
            this.queue.push(foo);
        }
        else{
            var that = this;
            foo(function(){
                that.executing = false;
                that.next();
            })
        }
    },
    
    next:function(){
        if(this.queue.length > 0){
            var foo = this.queue.shift();
            var that = this;
            
            foo(function(){
                that.executing = false;
                that.next();
            })
        }
    }
}

function a(success,failure){
    console.log('a');
    success();
}

function b(success,failure){
    console.log('b');
    success();
}


function c(success,failure){
    console.log('c');
    success();
}

// 使用

var queue = new ExecuteQueue();

queue.then(a).then(b).then(c);

//a
//b
//c



你可能感兴趣的:(JavaScript,框架设计)