使用键异步循环遍历数组

我有一组客户,我想遍历他们并为每个客户分配一个属性。通过 details 函数返回具有添加属性的客户对象


for (let i = 0; i < customers.length; i++)

{

    customers[i] = await details(customers[i]);

}

这就是我目前这样做的方式,但它是同步的。我希望列表中的所有对象都异步完成。我正在尝试使用异步库,但它只为我提供循环内可用的客户对象,因此客户数组永远不会改变。


async.forEachOf(customers, (customer, finished) async =>

{

    customer = await details(customer);

    finished();

});

否则我该怎么做?谢谢


呼啦一阵风
浏览 146回答 3
3回答

眼眸繁星

您不需要第三方库来完成此操作。只需使用Promise.all()和Array.prototype.map()。const customerDetails = await Promise.all(&nbsp; customers.map(customer => details(customer)));

一只斗牛犬

阿库不需要异步迭代项的阵列。例如,要异步处理此数组:const arr = [1, 2, 3];首先,从数组创建一个生成器,以便您可以为数组中的每个项目生成执行:/**&nbsp;* A convenience function for creating a ES2015 Generator to iterate over&nbsp;* items in an array.&nbsp;*&nbsp;* @template T&nbsp;* @param {T[]} value&nbsp;*/function* toIterator<T>(value: T[]) {&nbsp; const generator = value[Symbol.iterator]();&nbsp; for (let generated of generator) {&nbsp; &nbsp; yield generated;&nbsp; }}然后,异步迭代数组的关键是resolve在提供的handler./**&nbsp;* Provides the ability to process an iterator's values asynchronously&nbsp;* with a predicate, `hander`.&nbsp;*&nbsp;* @template T&nbsp;* @template TReturn&nbsp;* @template TNext&nbsp;* @param {Generator<T, TReturn, TNext>} generator&nbsp;* @param {(arg: T) => Promise<TReturn>} handler&nbsp;* @returns&nbsp;*/async function iterateAsynchronously<T, TReturn, TNext>(&nbsp; generator: Generator<T, TReturn, TNext>,&nbsp; handler: (arg: T) => Promise<TReturn>) {&nbsp; const iterate: () => Promise<TReturn> = async () => {&nbsp; &nbsp; const generated = generator.next();&nbsp; &nbsp; if (generated.done) {&nbsp; &nbsp; &nbsp; return generated.value;&nbsp; &nbsp; }&nbsp; &nbsp; return handler(generated.value).then(iterate);&nbsp; };&nbsp; return iterate();}如果您愿意,可以使用这些方法中的一种或两种来扩展全局数组。另一个例子。这将允许您在异步处理项目后将更多数组方法链接在一起:const run = async () => {&nbsp; const arr = [1, 2, 3, 4];&nbsp; console.log((await arr.iterateAsynchronously((val) => new Promise(r => {&nbsp; &nbsp; setTimeout(r, 2000);&nbsp; &nbsp; console.log('Processing', val);&nbsp; }))).reverse());}run();在这种情况下,由于使用返回数组本身的函数扩展修改了数组原型,因此您可以像以前一样将数组方法链接在一起。

青春有我

此代码将details()一个接一个地为每个客户运行,而无需等待前一个。您创建了一系列承诺并在最后等待它们const promises = [];for (let i = 0; i < customers.length; i++) {&nbsp; &nbsp; let p = new Promise(async (resolve, reject) => {&nbsp; &nbsp; &nbsp; customers[i] = await details(customers[i]);&nbsp; &nbsp; &nbsp; resolve();&nbsp; &nbsp; });&nbsp; &nbsp; promises.push(p);}await Promise.all(promises);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript