【发布时间】:2017-04-20 14:56:50
【问题描述】:
有一个带有deferred的函数调用了另一个带有deferred的函数:
var state = true;
var construct = function() {
var dfd = $.Deferred();
dfd
.then(function() {
return wakeUp();
})
.then(function() {
return makeCoffee();
})
.then(function() {
return conquireTheWorld();
})
.then(function() {
console.log("I'm done");
});
dfd.resolve();
}
var wakeUp = function() {console.log('Woke up');}
var makeCoffee = function() {console.log('Made some coffee');}
var conquireTheWorld = function() {
var dfd = $.Deferred();
if (state) {
dfd.then(function() {
return $.when(someAjax('http://babeljs.io')).done(function() {console.log("World done with AJAX");})
});
} else {
dfd.then(function() {
console.log("World done in a simple way");
});
}
dfd
.then(function() {
console.log("Moon done too");
});
return dfd.resolve();
}
var someAjax = function(url) {
return $.ajax({
type: 'GET',
url: url
});
}
不幸的是,在这种情况下,它卡在了conquireTheWorld 函数中:.done 的一部分 $.when 根本没有运行,其他部分在父函数之后执行。有控制台输出:
Woke up
Made some coffee
Moon done too //executed before ajax request complete
I'm done //executed before conquerTheWorld function ajax
World done with AJAX
如何等待ajax请求?我试图删除 $.when 并在另一个 .then 语句中处理(没有改变),或者返回 dfd.promise() 而不是 dfd.resolve() (它卡在那个函数中)。如何以正确的方式做到这一点?
【问题讨论】:
-
哇。该功能可以简化为
if (state) { return someAjax('http://babeljs.io').done(function () {console.log('ajax whatever');});} else { console.log('whatever'); }过度使用方法。 -
@KevinB 在 if/else 语句之后我还有一个操作,这样我应该复制它或将它分离到另一个函数,不是吗?