Is there a way, in a JavaScript object literal, to initialize some fields with the result of async functions while ensuring they will still run concurently?
Here is what I tried:
async function f() { /* ... */; return 0; }
async function g() { /* ... */; return 1; }
async function init() {
const o = { f: f(), g: g() };
return o;
}
init().then(console.log)
//> { f: Promise { ... }, f: Promise { ... } }
// XXX not what I want: I want *values* not promises
If I write the code above, f()
and g()
are resolved in parallel, but obj.f
and obj.g
will hold the promise returned by the function, not the resolved value.
On the other hand, with the syntax below I obtain an object whose fields contains values, but it seems to me the f()
and g()
calls were resolved sequentially. Or am I wrong here?
async function init() {
const o = { f: await f(), g: await g() };
return o;
}
init().then(console.log)
//> { f: 0, g: 1 }
// ??? did `f()` and `g()` run concurrently or sequentially here?