Javascript ES6承诺与地图

时间:2017-07-24 11:22:10

标签: javascript loops ecmascript-6 promise fetch

我正在尝试找出在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();
  });
};

2 个答案:

答案 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第二次[失败]回调。)

除了缺少错误处理之外,如果以上是您想要的,那么该代码就可以了。

相关问题