Search code examples
javascriptarrayses6-promise

How do I store data inside a promise in an array(JavaScript)?


the code below doesn't add anything to the array after being done. I thought by including another then would resolve the data and allow me to use it outside of the scope.

function getImgUrls(searchItems) {
  searchItems.forEach(currentItem => {
    let image;
    imgClient.search(currentItem, options).
    then(images => {
      return images[0].url;
    }).then(finalResult => {
      console.log(finalResult);
      pushToArray(finalResult);  
    })
    .catch(error => {console.log(error); });
  });
}


Solution

  • You have a whole bunch of promises so you will need to know when they are all done. The simplest way here is to use Promise.all(). And, since you're trying to accumulate an array of promises, it's best to use .map() instead of .forEach():

    function getImgUrls(searchItems) {
        return Promise.all(searchItems.map(currentItem => {
            return imgClient.search(currentItem, options).then(images => {
                //  make the url be the resolved value of the promise
                return images[0].url; 
            });
        }));
    }
    
    getImgUrls(...).then(urls => {
        console.log(urls);    // final array of urls
    }).catch(err => {
        console.log(err);
    });