【发布时间】:2021-04-24 22:40:17
【问题描述】:
我有一个要运行的承诺链,当它完成时,我 resolve 承诺(请参阅下面的代码以获取更多上下文),并期望我的 .then() 块运行......但它确实不是。
这是我的代码:
function notifications_for_each_in_array(iteration, the_array, error_array) {
return new Promise(function(resolve, reject) {
if(!iteration) iteration = 0;
var error_array = error_array || [];
var user_id = the_array[iteration];
$.ajax({
url: ".....my_url.....",
type: "PUT",
data: JSON.stringify({test: [user_id]}),
success: function() {
// ...
}
}).done(function(rez) {
error_array.push(rez);
iteration++;
console.log("will stop: " + (the_array[iteration] == undefined));
if(the_array[iteration] == undefined) { // reached the end
console.log("Resolving...");
resolve(error_array);
} else {
if(the_array[iteration] != undefined) {
console.log("Next: " + iteration);
notifications_for_each_in_array(iteration, the_array, error_array);
}
}
}).fail(function(err) {
console.error(err);
});
});
}
上面的函数可以工作,但是当我用.then() 调用它时,.then() 块不会运行。
在此示例中,我从未收到警报(PS:我还尝试将notifications_for_each_in_array 定义为async 函数,并使用await,但得到相同的结果):
notifications_for_each_in_array(0, [0,1,2,3], [])
.then(function(res) {
alert("here is then()"); // I never get alerted!
});
【问题讨论】:
-
你递归调用
notifications_for_each_in_array(iteration, the_array, error_array),但不要resolve它。 -
警告:
$.ajax返回一个thennable,你有explicit constructor antipattern here -
您可能不想同时拥有
success回调和done回调 -
@SebastianSimon 是正确的。另外,我不确定这里是否需要递归。似乎这段代码比它需要的更复杂。
-
@AlphaHowl 但这是解决一个不同的承诺,而不是顶级承诺。
标签: javascript asynchronous promise request resolve