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');
})
执行结果:
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步