简体   繁体   中英

Promise returns early - Map array with promises

We have the following code which makes an ajax post and downloads multiple files.

The promises do not have to wait for others to complete and should all complete asynchronously.

async function downloadAllFiles(fileIds, token) {
  var promises = fileIds.map(async fileId => {
    return await downloadIndividualFile(fileId, token);
  });
  Promise.all(promises).then(res => {
    return res;
  });
}

async function downloadIndividualFile(fileId, token) {
  return await downloadFile(fileId, token) // makes call to API post etc.
    .then(async result => {
      // handle the file download result
      // save file
    })
    .catch(error => {
      console.log(error);
    });
}

This is then called from a different file:

await downloadAllFiles(fileIds, token)
      .then(res => {
        console.log('result from download all');
        console.log(res);
      })
      .catch(error => {
        console.log(error);
      })
      .finally(() => {
        console.log('finally');
      });

What currently happens is the finally is called before the post promise is actually completed (called in the downloadFile api call).

How can the above be changed so that when await downloadAllFiles is called the finally is only called when all previous post requests are complete.

You need to return the promise in downloadAllFiles function. Update:

return Promise.all(promises).then(res => {
    return res;
});

Some refactoring on your code

function downloadAllFiles(fileIds, token) {
  var promises = fileIds.map(fileId => return downloadIndividualFile(fileId, token));
  return Promise.all(promises);
}

async function downloadIndividualFile(fileId, token) {
  try {
    const result = await downloadFile(fileId, token);
    // handle the file download result
    // save file
  } catch (error) {
      console.log(error);
  }
}

downloadAllFiles(fileIds, token)
  .then(res => {
    console.log('result from download all');
    console.log(res);
  })
  .catch(error => {
    console.log(error);
  })
  .finally(() => {
     console.log('finally');
  });

If you are using .then , you don't need await .

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