尽管阅读了六个小时(包括官方文档),但我仍然难以解决诺言的实现问题。(我得到了核心概念。)在函数X中,我有Y个Ajax调用。我已经能够确定何时完成所有Y ajax调用(尽管,我仍然不完全了解语法如何产生结果)。
但是,我仍然需要使函数X(另一个函数)的调用者知道所有Y ajax调用均已完成。这是一个简化的/半伪代码示例。(我想知道以前的尝试是否由于范围问题而失败,但是在看到的示例中,我没有看到将延迟的对象传递给函数。我决定将示例保持在“干净”之下,而不是显示特定的尝试失败。)
$.fn.SendEmails = function (emailsToSend) {
var emailSendingPromises = [];
$.each(emailsToSend, function (i, p) {
emailSendingPromises.push($.ajax({
// relevant stuff
})
.done( function () {
console.log('one email done');
})
.fail( function () {
console.log('one email failed');
}));
});
// when all promises have completed
$.when.apply($, emailSendingPromises).always(function () {
console.log('all emails completed');
// --- MAKE CALLER AWARE ALL EMAILS ARE COMPLETED ---
});
}
$.fn.AnotherFunction = function () {
$().SendEmails(emailsToSend);
// --- BECOME AWARE THAT ALL EMAILS ARE COMPLETED ---
// do other stuff only when all emails are completed AND some other things happen
}
非常感谢您的协助!:)
首先,尝试return
荷兰国际集团你$.when
在你的SendEmails
函数。然后,AnotherFunction
在进行此调用后,在您的中$().SendEmails(emailsToSend)
添加一个.then()
:
$().SendEmails(emailsToSend).then(function() { /* other stuff */});
在.then()
返回的承诺已得到解决后才会触发。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句