我正在尝试了解 Promise.all 的工作原理,看起来它应该很简单。我的理解是 Promise.all 接受一系列 promise ,然后同时执行它们。
这是我编写的一些代码,我通过 Node (8.10.0) 执行,我希望它能正常工作:
const getFirstPromise = function() {
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log("1");
resolve("First!"); // Yay! Everything went well!
}, 2500);
});
};
const getSecondPromise = function() {
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log("2");
resolve("Second!"); // Yay! Everything went well!
}, 250);
});
};
const getThirdPromise = function() {
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log("3");
resolve("Third!"); // Yay! Everything went well!
}, 1000);
});
};
const getFourthPromise = function () {
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log("4");
resolve("Fourth!"); // Yay! Everything went well!
}, 500);
});
};
const tasks = [
getFirstPromise,
getSecondPromise,
getThirdPromise,
getFourthPromise
];
Promise.all(tasks).then((result) => console.log("Done alling the promises: ", result)).catch(err => console.log(err));
如所写,这不会执行任何 promise 。
如果我将任务集合更改为如下所示:
const tasks = [
getFirstPromise(),
getSecondPromise(),
getThirdPromise(),
getFourthPromise()
];
然后所有的 promise 都会执行,但如果我注释掉 Promise.all 行,它们仍然会执行。
我所期望的是创建一个在调用 Promise.all 之前不会运行的 promise 集合。
请解释如何实现我的期望,或者解释我对 Promise.all 的理解有何缺陷,或者告诉我我还应该如何创建我的 promise 。
我对执行这一系列 promise 的无数其他方式不感兴趣。我只想了解在 Promise.all 执行之前我不希望 promise 代码运行的情况下 Promise.all 应该如何处理 promise 的集合。
最佳答案
你可以使用这个函数代替 Promise.all
var Task = {
all: function(tasks) {
return Promise.all(tasks.map((task) => task()));
}
};
并使用
const tasks = [
getFirstPromise,
getSecondPromise,
getThirdPromise,
getFourthPromise
];
Task.all(tasks).then((result) => console.log("Done alling the promises: ", result)).catch(err => console.log(err));
关于javascript - 我如何让 Promise.all 按预期执行我的 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50066102/