我正在尝试找出最有效的方法来等待 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();
});
};
最佳答案
如果你想同时运行所有的 promise 并在所有的 promise 都被解析时做一些事情,你可以使用 es2015 Promise.all()
:
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.all(urls.map(getThumb)).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);
});
};
关于带有 map 的 Javascript ES6 Promises,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45279327/