defered,promise回顾

defered,promise回顾

http://www.ruanyifeng.com/blog/2011/08/a_detailed_explanation_of_jquery_deferred_object.html
http://www.cnblogs.com/haogj/p/4480772.html

之前尝试过自己实现defered,现在再回顾一下

defered是为了解决异步回调的问题,之前的嵌套写法改成了链式写法,爽了很多。

其实也没有啥高深的东西,不过这想法真是,厉害了我的哥!

利用了闭包,异步事务完成后,调用相应的resolve/reject更新闭包defered对象的状态,从而激发相应callback的执行。

    var task = function() {
        var dtd = $.Deferred();
        setTimeout(function() {
            console.log('xxxx: ', '运行task');
            dtd.resolve('123123123');
        }, 3000);

        return dtd.promise();
    };
    $.when(task()).then(function(msg) {
        console.log('msg: ', msg);
        console.log('xxxx: ', '任务完成..1');
        return 'hahahah';//作为下一个callback的参数
    }).then(function(msg) {
        console.log('msg: ', msg);
        console.log('xxxx: ', '任务完成..2');
    })

执行结果:

posted @ 2016-10-27 11:12  CooMark  阅读(552)  评论(0编辑  收藏  举报