繁体   English   中英

带地图的Javascript ES6承诺

[英]Javascript ES6 Promises with map

我试图找出最有效的方法来等待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);
  });
};

有关该代码的一些说明,根据您的需要,这些注释可能会或可能不会成为问题:

  • test将以请求的URL的顺序结束(我很确定与URL在原始数组中的顺序相同,请参阅Promise.map文档 ),而不是被解析的顺序(如果你在意)
  • test将包含URL,即使它们无法加载也是如此,因为您是在映射功能中将其推送的
  • 您正在使用响应的文本(以及图像数据)来解决您的个人承诺,但不能在任何地方使用该文本
  • 您正在使用不必要的包装器函数,不需要围绕getThumb的包装器:

     Promise.map(urls, getThumb).then(function() { console.log(test); }); 

一个明确的问题:

  • 你不处理失败:你需要一个catch (或then与第二[失效]回调)。

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

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM