簡體   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