Search code examples
asynchronousasync-awaitpromisecallbackes6-promise

Multiple promises fulfilled and saved in NodeJS


I have this part of code that work but strangely the latest step of outputting the result doesn't work.. When i try to log the first element of array it returns undefined bacause the execution is asynchronous. I thought to build a series of nested callbacks but I think that is a bad practice. Is there any other way to makes it work without create nested promise callbacks?

CODE:

  var ImgGalleyURL = [];
  //CONTROLLO SE SONO STATE INSERITE IMMAGINI DA CARICARE E LE CARICO
  if (postwp.postImgGallery1 != null && postwp.postImgGallery1 != "") {
    msg.createMedia(postwp.postImgGallery1).then((imgURL)=>ImgGalleyURL.push(imgURL));
  }
  if (postwp.postImgGallery2 != null && postwp.postImgGallery2 != "") {
    msg.createMedia(postwp.postImgGallery2).then((imgURL)=>ImgGalleyURL.push(imgURL));
  }
  if (postwp.postImgGallery3 != null && postwp.postImgGallery3 != "") {
    msg.createMedia(postwp.postImgGallery3).then((imgURL)=>ImgGalleyURL.push(imgURL));
  }
  if (postwp.postImgGallery4 != null && postwp.postImgGallery4 != "") {
    msg.createMedia(postwp.postImgGallery4).then((imgURL)=>ImgGalleyURL.push(imgURL));
  }
  if (postwp.postImgGallery5 != null && postwp.postImgGallery5 != "") {
    msg.createMedia(postwp.postImgGallery5).then((imgURL)=>ImgGalleyURL.push(imgURL));
  }
  console.log(ImgGalleyURL[0] + "this is the first image loaded");

Thank you all


Solution

  • I think you're looking for Promise.race:

    const promises = [];
    for (let i=1; i<=5; i++) {
      const propName = "postImgGallery" + i;
      if (postwp[propName] != null && postwp[propName] != "") {
        promises.push(msg.createMedia(postwp[propName]));
      }
    }
    Promise.race(promises).then(firstUrl => {
      console.log(firstUrl + "this is the first image loaded");
    });
    Promise.all(promises).then(imgGalleryURLs => {
      console.log("All images ("+ imgGalleryURLs.join(", ") + ") loaded");
    });
    

    You were trying to log the first value of the array when none of the promises was fulfilled yet, so it was still empty.