我有一个对象数组,每个我执行一个promise。然后,如果一切都解决了,我希望在.then
中进行Promise.all
来电。问题是,通过以下示例,我只获得输出
所有在方法2中完成
我认为以下代码几乎是解释性的,但简而言之,我所做的是:
vals
,我想根据每个对象创建一个承诺。vals.map
根据vals
vals
迭代for
并在每次迭代中推送新的承诺。这段代码有什么问题?为什么它只适用于方法2?
#!/usr/bin/env node
let vals = [
{
name: "name1"
},
{
name: "name2"
},
{
name: "name3"
}
];
function newPromise(obj) {
return new Promise((resolve) => Promise.resolve(obj.name))
}
/**
* Approach 1: use .map function to get an array of promises
*/
let promises = vals.map((item) => newPromise(item));
Promise.all(promises)
.then(() => console.log("All done in approach 1"))
.catch(() => console.log("Error in approach 1"));
/**
* Approach 2: iterate through vals using a for an push a new promise for the promises array
*/
let promises2 = [];
for (let i = 0 ; i < vals.length; i++) {
promises.push(newPromise(vals[i]));
}
Promise.all(promises2)
.then(() => console.log("All done in approach 2"))
.catch(() => console.log("Error in approach 2"));
我使用节点8.9.1和ES6(本机Promises)。
答案 0 :(得分:3)
你有两个轻微的错误,这些错误会使作品变得混乱并且让人感到困惑。
首先,您的第二种方法不应工作,因为您不小心将其推送到promises
进行第二种方式而不是promises2
,所以您正在做Promise.all()
有一个空数组,这就是它工作的原因。
然后,由于你如何创造承诺,两者都不起作用的原因。您在Promise.resolve()
内嵌套了new Promise()
,但这不起作用。你可以使用:
return new Promise(resolve => resolve(obj.name));
或
return Promise.resolve(obj.name);
那些是等价的。将它们放在里面,你从未在resolve()
中调用正确的new Promise()
函数,所以没有任何实际解决过。
let vals = [
{
name: "name1"
},
{
name: "name2"
},
{
name: "name3"
}
];
function newPromise(obj) {
return new Promise((resolve) => resolve(obj.name))
}
/**
* Approach 1: use .map function to get an array of promises
*/
let promises = vals.map((item) => newPromise(item));
Promise.all(promises)
.then(() => console.log("All done in approach 1"))
.catch(() => console.log("Error in approach 1"));
/**
* Approach 2: iterate through vals using a for an push a new promise for the promises array
*/
let promises2 = [];
for (let i = 0 ; i < vals.length; i++) {
promises2.push(newPromise(vals[i]));
}
Promise.all(promises2)
.then(() => console.log("All done in approach 2"))
.catch(() => console.log("Error in approach 2"));
答案 1 :(得分:0)
您的newPromise
功能存在问题。尝试删除Promise.
。
对于第二种方法,您还必须推送正确的数组:promises2
let vals = [
{
name: "name1"
},
{
name: "name2"
},
{
name: "name3"
}
];
function newPromise(obj) {
return new Promise((resolve) => resolve(obj.name))
}
/**
* Approach 1: use .map function to get an array of promises
*/
let promises = vals.map((item) => newPromise(item));
Promise.all(promises)
.then(() => console.log("All done in approach 1"))
.catch(() => console.log("Error in approach 1"));
/**
* Approach 2: iterate through vals using a for an push a new promise for the promises array
*/
let promises2 = [];
for (let i = 0 ; i < vals.length; i++) {
promises2.push(newPromise(vals[i]));
}
Promise.all(promises2)
.then(() => console.log("All done in approach 2"))
.catch(() => console.log("Error in approach 2"));