簡體   English   中英

使用香草承諾的 RSVP 哈希

[英]RSVP hash using vanilla promises

RSVP lib有一個散列的 promises helper,它允許“檢索”promise 引用:

var promises = {
  posts: getJSON("/posts.json"),
  users: getJSON("/users.json")
};

RSVP.hash(promises).then(function(results) {
  console.log(results.users) // print the users.json results
  console.log(results.posts) // print the posts.json results
});

有沒有辦法用香草承諾(在現代 ES 中)做這樣的事情?

OOTB? 不,只有Promise.all ,但它接受一個數組,而不是一個字典。 但是你可以創建一個輔助函數,它接受一個Promise.all字典,轉換為數組,在它上面運行Promise.allthen處理一個, then將結果數組轉換回字典。

實施起來並不難。

async function hash(promiseObj) {
  // Deconstitute promiseObj to keys and promises
  const keys = [];
  const promises = [];
  Object.keys(promiseObj).forEach(k => {
    keys.push(k);
    promises.push(promiseObj[k]);
  });
  // Wait for all promises
  const resolutions = await Promise.all(promises);
  // Reconstitute a resolutions object
  const result = {};
  keys.forEach((key, index) => (result[key] = resolutions[index]));
  return result;
}

hash({
  foo: Promise.resolve(8),
  bar: Promise.resolve(16),
}).then(results => console.log(results));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM