好吧,我已经阅读了 1,000,000 多篇关于 jQuery deferreds 和/或 Promise 的文章,但我仍然发现一些问题。
functionOne() {
var deferred = $.Deferred();
var request = $.ajax({
url: 'http://example.com/mypath/etc'
});
request.done(function(data) {
// TODO: I've got stuff here that takes a while.
deferred.resolve();
});
return deferred.promise();
}
functionTwo() {
// Something that depends on the others being finished.
}
$.when(
functionOne(),
anotherLongRunningFunctionWithAjax())
.then(
functionTwo()
);
我需要“当”中的任何函数在“然后”开始之前完全完成(.ajax 完成)。然而,promise 立即返回(如预期),但 functionTwo 启动,即使 functionOne 尚未调用“done”。
我确信这是对延迟和调用链的根本误解。
编辑:
function functionOne() {
console.log('functionOne called');
var request = $.ajax({
url: 'http://example.com/mypath/etc'
});
request.done(function(data) {
console.log('Starting Done.');
setTimeout(function () {
console.log('Done finished.');
}, 5000);
});
console.log('Returning promise.');
return request;
}
function functionTwo() {
console.log('functionTwo called');
}
$.when(functionOne()).then(functionTwo());
在控制台中给我这个:
functionOne called
Returning promise.
functionTwo called (should be called after Done is finished.)
Starting Done.
Done finished.
最佳答案
根据您编辑的代码,存在两个问题:
functionOne 中的计时器在请求解决后启动,但您返回请求。因此,无论计时器发生什么......它与返回的 promise 无关,当时已经解决了。
您立即调用 functionTwo,而不是传递 $.when promise 回调的函数引用
这是工作代码:
function functionOne() {
console.log('functionOne called');
console.log('Returning promise.');
return $.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1'
}).then(function(data) {
console.log('Starting Done.');
var dfd = $.Deferred();
setTimeout(function () {
console.log('Done finished.');
dfd.resolve(data); // indicate when you are done
}, 2000); // 2 seconds will do ;-)
return dfd.promise(); // you need to return a promise again
});
}
function functionTwo() {
console.log('functionTwo called');
}
// don't call functionTwo immediately, leave that to the promise to do:
$.when(functionOne()).then(functionTwo);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
关于javascript - jQuery 延迟/ promise 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42032373/