我正在尝试找到在map函数中等待所有数据获取完成并继续执行的最有效方法。我尝试使用'bluebird'库,并得出以下结论。
这是否有效,是否有更好的方法来实现这一点?
let urls = ['https://static.pexels.com/photos/36753/flower-purple-lical-blosso.jpg', 'https://static.pexels.com/photos/36764/marguerite-daisy-beautiful-beauty.jpg', 'https://static.pexels.com/photos/65609/tulip-tulips-sharpness-game-flower-65609.jpeg'];
let test = [];
Promise.map(urls, function(url) {
// Promise.map awaits for returned promises as well.
return getThumb(url);
}).then(function() {
console.log(test);
});
function getThumb(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => resolve(xhr.responseText);
xhr.onerror = () => reject(xhr.statusText);
xhr.send();
test.push(url);
});
https://jsfiddle.net/v80wmmsv/4/
非常感谢 :)
编辑:
以下是最终结果:
let urls = ['https://static.pexels.com/photos/36753/flower-purple-lical-blosso.jpg', 'https://static.pexels.com/photos/36764/marguerite-daisy-beautiful-beauty.jpg', 'https://static.pexels.com/photos/65609/tulip-tulips-sharpness-game-flower-65609.jpeg'];
Promise.map(urls, getThumb).then(function(data) {
console.log(data.length);
}).catch(e => console.error(e));
function getThumb(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => resolve(xhr.responseText);
xhr.onerror = () => reject(xhr.statusText);
xhr.send();
});
};