I am wondering how to assign values to multiple different keys asynchronously with Await/Async.
Initially I had imagined merely calling the Async function would assign the values such as below:
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")
}
}
Obviously this isn't how async works since await must be called to actually retrieve the values from the resolved promise. But it did asynchronously retrieve and assign the values to the key (albeit promises instead of their values) which is sort of what I was looking for.
So the question is how do I actually get the values assigned to the keys asynchronously?
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")
}
}
I tried this and it did assign the values but clearly it is completely counterintuitive since it's synchronous sequential at that point.
Typically for just standard variables assigned to async functions, I would just add the function calls to an array and destructure the functions into variables using
const asyncFunctions = [val1(), val2(), val3()];
const [key1,key2,key3] = await Promise.all(asyncFunctions);
How do I accomplish something similar for objects?