I have two asynchronous operations such that the invocation of the second one uses input from the output of the first. To implement such invocations with async
and await
, it seems, it won't turn out to be too different from callbacks.
Consider this.
async function loop(label, I) {
console.log('%s - Looping for %d times.', label, I)
console.time(label)
for (i = 0; i < I; ++i) {
}
return Promise.resolve(I)
}
//
async function demo0() {
// Refer - https://stackoverflow.com/a/45479579/919480
let I0 = loop('01', 10)
let I1 = loop('02', I0 * 1000)
await I0
await I1
}
//
async function demo1() {
// Refer - https://stackoverflow.com/a/45479579/919480
let I0 = loop('11', 10)
await I0
let I1 = loop('12', I0 * 1000)
await I1
}
//
async function demo2() {
await loop('21', 10).then(async (i) => {
await loop('22', i * 1000)
})
}
//
(async () => {
await demo0()
await demo1()
await demo2()
})()
Result:
01 - Looping for 10 times.
02 - Looping for NaN times.
11 - Looping for 10 times.
12 - Looping for NaN times.
21 - Looping for 10 times.
22 - Looping for 10000 times.
The second loop should iterate based on a value passed on by the first loop. In demo0
and demo1
, the second loop receives a NaN
because they are triggered simultaneously. Only in demo2
, does the second loop receive the correct value. One could have achieved this behavior with callbacks too.
Is there a async/await
way to achieve this behavior?