使用带有 Promise.all() 的配置对象

using a config object with Promise.all()

我正在考虑使用 Promise.all() 从多个端点获取数据。使用 Promise.all() 返回一个数组,您可以析构该数组中的项目,例如

const [fetch1, fetch2] = Promise.all(urls.map(url => fetch(url)))

我正在寻找使用配置对象动态命名那些解构项目(name1 和 name2)的方法。

const urls = [
  {
    name: 'google',
    url: 'https://www.google.com'
  },
  {
    name: 'bbc',
    url: 'https://www.bbc.co.uk'
  }
]

const [google, bbc] = Promise.all(urls.map(url => fetch(url.url)))

在上面的示例中,从 promise.all 解构的项目应该使用 urls 数组中的名称,即 urls.name

本质上,我正在寻找一种方法来在传递给 promise.all()

的配置对象中命名我的导出

主要原因是从这些承诺中返回的数据将以 urls 配置对象中指定的名称作为键控。所以我们也可以做

const data = Promise.all(urls.map(url => fetch(url.url)))
console.log(data.google || data.bbc)

应该这样做:

const fetchUrl = (url) => fetch(url.url).then((response) => ({ [url.name]: response }));

const mergeResults = (results) => results.reduce(
  (mergedResults, result) => ({ ...mergedResults, ...result }),
  {}
);

const data = Promise
  .all(urls.map(fetchUrl))
  .then(mergeResults)
  .then((data) => {
    console.log(data.google || data.bbc);
  });

Bergi 的更新:

const data = Promise
  .all(urls.map(fetchUrl)) // same as above
  .then((results) => Object.assign({}, ...results)) // elegance++
  .then((data) => {
    console.log(data.google || data.bbc);
  });