jquery自定义延迟函数 [英] jquery custom deferred functions
本文介绍了jquery自定义延迟函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有三个函数正在尝试运行,前两个正在做一些异步的东西,需要第三个使用的数据。我希望只有当1和2都完成时才会触发第三个函数。这是一般结构,但最终功能是在1和2结束前开始。
I have three functions i'm trying to run, the first two are doing some async stuff that need data for the third to use. I want the third function to fire only when 1 and 2 are both done. this is the general structure but the final function is firing before 1 and 2 finish.
function run() {
var data1 = {};
var data2 = {};
$.when(first(), second()).done(constructData());
function first() {
var d = new $.Deferred();
//do a bunch of stuff async
data1 = {};
d.resolve();
}
function second() {
var d = new $.Deferred();
//do a bunch of stuff async
data2 = {};
d.resolve();
}
function constructData() {
//do stuff with data1 and data2
}
}
答案是不立即调用构造数据
Answer was to not call construct data immediately
$.when(first(), second()).done(constructData);
推荐答案
您应该返回promise对象。你在这一行中也有错误:
You should return promise object. You also have an error in this line:
$.when(first(), second()).done(constructData());
它应该是
$.when(first(), second()).done(constructData); // don't call constructData immediately
所有这一切可能是:
function run() {
var data1 = {};
var data2 = {};
$.when(first(), second()).done(constructData);
function first() {
return $.Deferred(function() { // <-- see returning Deferred object
var self = this;
setTimeout(function() { // <-- example of some async operation
data1 = {func: 'first', data: true};
self.resolve(); // <-- call resolve method once async is done
}, 2000);
});
}
function second() {
return $.Deferred(function() {
var self = this;
setTimeout(function() {
data2 = {func: 'second', data: true};
self.resolve();
}, 3000);
});
}
function constructData() {
//do stuff with data1 and data2
console.log(data1, data2);
}
}
这篇关于jquery自定义延迟函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文