下面的代码在完成后不会向数组添加任何内容。我认为通过包含另一个然后可以解决数据并允许我在范围之外使用它。
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); });
});
}
你有一大堆承诺,所以你需要知道它们什么时候完成。这里最简单的方法是使用Promise.all()
. 而且,由于您正在尝试积累一系列承诺,因此最好使用.map()
而不是.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);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句