我有一个值数组,我想创建一个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]
答案 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]