Javascript 如何使用循环通过异步函数更改数组中项的属性?
这是基本状态。一个数组和一个异步函数Javascript 如何使用循环通过异步函数更改数组中项的属性?,javascript,asynchronous,Javascript,Asynchronous,这是基本状态。一个数组和一个异步函数 let arr1 = [{num: 1}, {num: 2}, {num: 3}] function asyncFunWithPromise(index) { return new Promise((resolve, reject) => { setTimeout(() => { resolve(index) return index; }, 500); }) } 我希望得到这样的东西 [ {
let arr1 = [{num: 1}, {num: 2}, {num: 3}]
function asyncFunWithPromise(index) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(index)
return index;
}, 500);
})
}
我希望得到这样的东西
[ { num: 1, result: 0 }, { num: 2, result: 1 }, { num: 3, result: 2 } ]
下面的函数可以工作,但我不知道所有这些异步函数何时才能完成
arr1.forEach(async (listItem, index) => {
console.log(index)
listItem.result = await asyncFunWithPromise(index)
});
console.log(arr1) // [ { num: 1 }, { num: 2 }, { num: 3 } ],async Func haven't finish
这是可行的,但是很慢,就像串行执行一样
(async () => {
for (let index = 0; index < arr1.length; index++) {
console.log(index)
const currentItem = arr1[index];
currentItem.result = await asyncFunWithPromise(currentItem.num)
}
})()
这是另一种方法,使用Promise.all和Array.map,我不知道这是否是一种好方法
const functionWithPromise = item => {
return new Promise((resolve, reject) => {
setTimeout(() => {
item.result = item.num + ':async done'
resolve(item)
return;
}, 500);
})
}
const getData = () => {
return Promise.all(arr1.map(item => functionWithPromise(item)))
}
getData().then(data => {
console.log(data) // get a new array here
})
任何人都可以共享您的解决方案吗?如果我们可以返回具有更新属性的新数组。我们可以使用功能性方法
let arr = [ { num: 1, result: 0 }, { num: 2, result: 1 }, { num: 3, result: 2 } ];
arr = await Promise.all(arr.map(async i => {
// ... do async logic in here
return { ...i, result: 'async done'}
})
如果我们可以返回新的数组,带有更新的属性。我们可以使用功能性方法
let arr = [ { num: 1, result: 0 }, { num: 2, result: 1 }, { num: 3, result: 2 } ];
arr = await Promise.all(arr.map(async i => {
// ... do async logic in here
return { ...i, result: 'async done'}
})
在我看来,你的较低代码非常完美。我不会做任何根本不同的事情。你的低级代码在我看来近乎完美。我不会做任何根本不同的事情。