简体   繁体   中英

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); }); }); } 

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);
});

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