gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:17:33 25 4
gpt4 key购买 nike

<分区>

我正在考虑使用 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() 的配置对象中命名我的导出

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com