简体   繁体   English

如何在数组中的诺言中存储数据(JavaScript)?

[英]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() . 这里最简单的方法是使用Promise.all() And, since you're trying to accumulate an array of promises, it's best to use .map() instead of .forEach() : 并且,由于您要累积一个.forEach()数组,因此最好使用.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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我想用(new Promise)将数据存储在变量中吗? javascript - I want to store the Data inside the variables with (new Promise)? javascript 如何在变量中存储 promise object - How do I store a promise object inside a variable 在 Javascript 中使用 promise.all 时,如何从承诺数组中访问获取数据 - How do I access fetch data from an array of promises when using promise.all in Javascript 如何将图像存储在 JavaScript 的数组中 - How do I store images in an array for JavaScript 那我怎样才能将数据推送到Promise中的数组中呢? - How can I push data to an array inside a promise then? 如何在 Javascript 中的 Promise 值中获取数据? - How to get data inside a Promise Value in Javascript? 如何访问 Javascript 中数组内部的元素? - How do I access an element inside of an array that is inside of an array in Javascript? 如何在promise里面做promise - How to do promise inside promise 如何在 javascript 中存储作为 ajax 查询从 JSON 中提取数据的结果的对象数组? - How do I store an array of objects that are a result of an ajax query pulling data from JSON in javascript? 如何将单选按钮的值存储在数组中 - How do I store the values of radio buttons inside an array
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM