【发布时间】:2018-07-07 08:19:15
【问题描述】:
我想在所有承诺都解决或拒绝时继续,并在最后显示字符串“##### should be final call ####”。
TL;DR;
我忘记在 map 函数中返回 promise。
我正在尝试使用这种方法: Wait until all ES6 promises complete, even rejected promises
下面的代码有什么问题?
我希望 Promise.all() 的 .then 处理程序最终会被调用,毕竟其他的。
结果变量包含一个未定义值的数组。
console.clear();
$(document).ready(function () {
var url = "https://httpbin.org/get?";
a = [];
a.push(new Promise(function (resolve, reject) {
$.get(url + Math.random()).then((res) => resolve()).fail(() => {
reject();
});
}));
a.push(new Promise(function (resolve, reject) {
$.get(url + Math.random()).then((res) => resolve()).fail(() => {
reject();
});
}));
var mr = getPromise();
function getPromise() {
var promise = new Promise(function (resolve, reject) {
window.setTimeout(function () {
reject();
}, 1000);
});
return promise;
}
a.push(mr);
a.push(new Promise(function (resolve, reject) {
$.get(url + Math.random()).then((res) => resolve()).fail(() => {
reject();
});
}));
a.push(new Promise(function (resolve, reject) {
$.get(url + Math.random()).then((res) => resolve()).fail(() => {
reject();
});
}));
Promise.all(a.map((p) => {
p.catch((e) => {
console.log("failed promise catch");
});
}))
.then((results) => {
console.log("##### should be final call ####");
})
.catch((e) => {
console.log("final catch block executed");
});
}); // ready end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
【问题讨论】:
-
这在 NodeJS 中按预期工作。奇怪的是它在浏览器中失败了!
标签: javascript jquery promise es6-promise