function addNewProperty(arr) { return new Promise((resolve) => { const result = []; arr.forEach(async (item) => { const newItem = await asyncFunction(item); newItem.newProperty = "new value"; result.push(newItem); if (result.length === arr.length) { resolve(result); } }); }); }

async function asyncFunction(item) { return new Promise((resolve) => { setTimeout(() => { resolve(item); }, 1000); }); }

const arr = [1, 2, 3, 4];

async function main() { const result = await addNewProperty(arr); console.log(result); }

main()

js异步获取一个数组在循环通过异步函数将数组中的每个数据添加一个新属性返回整个数组

原文地址: https://www.cveoy.top/t/topic/gY9l 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录