简体   繁体   English

异步/等待解析JSON

[英]Async/await parsing json

So i have a piece of code like here and need to refactor it to use map/forEach. 所以我有一段像这里的代码,需要重构它以使用map / forEach。

       async function asyncForEach(array, callback) {
          for (let index = 0; index < array.length; index++) {
              await callback(array[index], index, array);
          }
       }

But when i use map like below it just parses the whole json without waiting for individual entries of the array to send each entry with delay in callback function. 但是当我使用如下所示的map时,它只是解析整个json,而无需等待数组的各个条目在回调函数中延迟发送每个条目。

      async function asyncForEach(array, callback) {
       await array.map(async (item, index) => {
         await callback(array[index], index, array);
       });
      }

Any help would be appreciated. 任何帮助,将不胜感激。

You have to use Promise.all as await on an array (although it contains promises) does nothing: 您必须在阵列上使用Promise.all进行await (尽管它包含promise),但不会执行任何操作:

 await Promise.all(array.map(/*...*/));

I'd write it as: 我将其写为:

  const asyncForEach = (array, callback) =>
     Promise.all(array.map(callback));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM