我正在尝试找出在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();
});
};
答案 0 :(得分:1)
如果您想要同时运行所有承诺并在解决所有承诺后执行某些操作,则可以使用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);
});
};
答案 1 :(得分:1)
有关该代码的一些注意事项,根据您的需要可能会出现问题,也可能不会出现问题:
test
将按照请求顺序结束网址(我非常确定它们与原始数组中的顺序相同,查看Promise.map
documentation),不是他们被解决的顺序(如果你关心)test
将包含URL,即使它们无法加载,因为您正在推送映射函数您正在使用不必要的包装函数,不需要getThumb
周围的包装器:
Promise.map(urls, getThumb).then(function() {
console.log(test);
});
还有一个明确的问题:
catch
(或then
第二次[失败]回调。)除了缺少错误处理之外,如果以上是您想要的,那么该代码就可以了。