<分区>
我想知道如何使用 Await/Async 将值异步分配给多个不同的键。
最初我以为只要调用 Async 函数就会分配如下值:
const getMetrics = async (metric, key) => {
const rawResponse = await fetch(`http:/localhost:8080/${metric}`,
{
method: 'POST'
body: JSON.stringify({
projects:[
{
name: key
}]
}
)
});
return await rawResponse.json();
};
const metrics = {
metric1: {
key1: getMetrics("metric1", "key1"),
key2: getMetrics("metric1", "key2"),
key3: getMetrics("metric1", "key3")
},
metric2: {
key1: getMetrics("metric2", "key1"),
key2: getMetrics("metric2", "key2"),
key3: getMetrics("metric2", "key3")
}
}
显然这不是 async 的工作方式,因为必须调用 await 才能从已解析的 promise 中实际检索值。但它确实异步检索值并将值分配给键(尽管是 promise 而不是它们的值),这正是我一直在寻找的东西。
所以问题是我实际上如何异步获取分配给键的值?
const metrics = {
metric1: {
key1: await getMetrics("metric1", "key1"),
key2: await getMetrics("metric1", "key2"),
key3: await getMetrics("metric1", "key3")
},
metric2: {
key1: await getMetrics("metric2", "key1"),
key2: await getMetrics("metric2", "key2"),
key3: await getMetrics("metric2", "key3")
}
}
我试过了,它确实分配了值,但显然它完全违反直觉,因为它在那个时候是同步顺序的。
通常对于分配给异步函数的标准变量,我只是将函数调用添加到数组并使用
将函数解构为变量const asyncFunctions = [val1(), val2(), val3()];
const [key1,key2,key3] = await Promise.all(asyncFunctions);
我如何为对象完成类似的事情?