带有 map 的 Javascript ES6 Promises

标签 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();
  });
};

最佳答案

如果你想同时运行所有的 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/

相关文章:

php - 将行标记为重要并在每次加载时保存它

javascript - 动态地使网页垂直适合浏览器

javascript - KnockoutJS foreach 绑定(bind) : cannot apply bindings multiple times to same element

loops - 在以下方面,WaitGroup不受双重尊重

javascript - 我可以绕过可选参数并仍然在 Javascript 中设置剩余参数吗?

javascript - 对象的可配置属性和可写属性之间的区别

javascript - 作品集模板: display number of posts based on the day of the week?

javascript - 循环这个嵌套的 obj 构建器函数?

java - 比较两个数组,增加计数器

javascript - ES6 对象.assign() : why do undefined properties override defined properties?