Array.prototype.map不能用于Promise?

时间:2017-01-01 08:23:15

标签: javascript arrays promise

我有一个值数组,我想创建一个promises数组来进行并行调用。但为什么地图功能不起作用?

let myArray = [1,2,3];
myArray.map((n) => {
    return new Promise((resolve, reject) => {
        resolve(n);
    });
});
console.log(myArray); // [1,2,3]

但是当我尝试将Promise推送到数组时可以按预期工作。

let myArray = [1,2,3];
let pArray = []
for(let n of myArray){
    pArray.push(new Promise((resolve, reject) => {
        resolve(i);
    }));
}
console.log(pArray); // [Promise,Promise,Promise]

2 个答案:

答案 0 :(得分:2)

这样做,因为map不修改数组:

let myArray = [1,2,3];
let promiseArray = myArray.map((n) => {
    return new Promise((resolve, reject) => {
        resolve(n);
    });
});
console.log(promiseArray);

答案 1 :(得分:2)

您需要指定map的结果。

let myArray = [1, 2, 3];
let pArray = myArray.map((n) => {
  return new Promise((resolve, reject) => {
    resolve(n);
  });
});
console.log(pArray); // [Promise,Promise,Promise]