简体   繁体   中英

Using async/await with a for in loop

I have an Object that name is uploadedFiles. when I run this code first run console.log then run the for so I get the empty array. how can I solve the problem

 let orderFilesData = [];
      for (let key in uploadedFiles) {
        uploadedFiles[key].map(async (file) => {
          let id = file.id;
          const orderFile = await this.orderFileRepository.findOne(id);
          orderFile.order = order;    
          await this.orderFileRepository.save(orderFile);
          orderFilesData.push(orderFile.fileUrl);
        });
      }
console.log(orderFilesData);

Since you do not return any data from the map, try using a foreach loop. Since you use an async function, what you set in orderFilesData will be an array of promises, and you'll have to await them. The simplest solution is to use Promise.all the array (console.log(Promise.all(orderFilesData)) should do what you want)

I suspect that the problem is that Array.map is async, so even though each one of the calls to save has await in front of it, iterating the elements and calling the anonymous function inside the .map is done in an async manner.

Try replacing uploadedFiles[key].map with a simple for loop and I believe that it'll fix the issue.

when array.map is used with async function it returns back a list of promises that is not runned. You'll have to start the process with Promise.All (or other).

Try this inside your for loop

 const uploadPromises = uploadedFiles[key].map(async (file) => {
       ...
  });
  await Promise.All(uploadPromises)

uploadedFiles seem to be an object, where the values of the keys are arrays? So if you call uploadedFiles[key].map(...) you are creating an array of promises where each of them seems to be awaited. But as the callback of map is asynchronous, you are in fact not awaiting. The simplest would be using Promise.all() to await all promises in the array of promises resulting from map.

  let orderFilesData = [];
  for (let key in uploadedFiles) {
    await Promise.all(uploadedFiles[key].map(async (file) => {
      let id = file.id;
      const orderFile = await this.orderFileRepository.findOne(id);
      orderFile.order = order;    
      await this.orderFileRepository.save(orderFile);
      orderFilesData.push(orderFile.fileUrl);
    }));
  }
 console.log(orderFilesData);

But for this to work, make sure the surrounding function is async

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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