Search code examples
node.jsasync-awaitpromise

promise.all with loop still get pending in node.js


This app function is about uploading multiple images, the image upload API can only upload one image each time. when uploading multiple images, trying to loop over the images and sequentially upload them one by one.

This is the example code.

let urls =   Promise.all(
   _.map(files, async function (file) {
    let url = await minioService.uploadFile( file.originalname, file.path);
    fs.unlinkSync(file.path);
    return url;
  })
);
console.log('upload success ',urls );

Since the uploading API - minioService.uploadFile is async and wait, so use Promise.all, but the return result from Promise.all is still pending.

upload success  Promise { <pending> }

How would I try to solve this issue


Solution

  • Promise.all needs to be awaited as well. Also you can use native .map function

    let urls = await Promise.all(
      files.map(async function (file) {
        let url = await minioService.uploadFile(file.originalname, file.path);
        fs.unlinkSync(file.path);
        return url;
      })
    );
    
    console.log('Upload success', urls);