I've read many articles on promises and async/await. They all seem to deal with working with APIs that return promises and how to work with those promises. I'm still a little confused.
Lets say I have a function that contains three (3) loops. Hypothetically, each loop does some work that takes five (5) seconds to complete, pushing the results of each iteration into an array for that loop. This work happens synchronously (loop 1 runs, followed by loop 2 and then loop 3).
The function then does something with the results of all three loops before returning. The total hypothetical execution time is around sixteen (16) seconds.
If the loops were put into their own functions, wrapped in a promise and then awaited inside an async function
using await Promise.all
(before doing something with the results), would they be executed in parallel (because they are in the event loop, not the call stack) and once all three (3) promises resolved, the function would continue? Is this faster than the whole processes being synchronous?
I guess I am confused as to when/why you'd want to create your own promises from synchronous JS?
function loop1() {
return new Promise((resolve, reject) => {
let loop1Counter = 0
const loop1Array = []
while (loop1Counter < 10 **8) {
// Do some work
loop1Array.push(resultOfWork)
}
loop1Counter += 1
resolve(loop1Array)
}
}
async function test() {
const promisesToAwait = [loop1(), loop2(), loop3()]
const results = await Promise.all(promisesToAwait)
// Do some work with results
return something
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…