2

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
}
Cazineer
  • 2,235
  • 4
  • 26
  • 44

1 Answers1

3

JavaScript execution is single threaded. This means that without using a mechanism such as a WebWorker none of the javascript code will execute in parallel. With that said there are a few reasons for executing synchronous javascript with async code such as promises.

  1. Your code takes a while to execute.

Javascript execution shares the same thread as with the UI in browsers. This means that if your code takes 5 seconds to execute the users browser will be blocked for the duration. You could instead break up the execution into multiple asynchronously executed blocks which will allow the UI to remain responsive.

  1. You are participating in a promise chain from existing async functions.

It is sometimes necessary to intermix async and synch code. Promises allow you to compose both async and synch code into an execution chain without having to have hard coded dependencies.

  1. You are running into stack size limitations.

Depending on how your code and libraries are written sometimes you may have run away stacks which can lead to stack size exceptions or just excessive memory usage. By executing a piece of code asynchronously it gains its own new stack.

  1. You are executing code in a library/framework that expects your code to be executing asynchronously.

You can translate synch code into async code but not the other way around. Therefore some libraries that execute code you have written(as a delegate) may require your code to be async to support the async use cases. Some libraries attempt to be intelligent about this and adapt based on your return type but not all of them are this smart.

Deadron
  • 5,135
  • 1
  • 16
  • 27
  • So basically, all that wrapping a `while` loop in a promise does, is makes it asynchronous, which pushes it on to the event loop so the rest of the code can execute and when finished, the promises in the call stack will get executed in the order they were pushed onto the stack? – Cazineer May 10 '18 at 19:18
  • At 12:16 in this video, Philip talks about the Web APIs having threads of their own, which would allow for parallel execution of those APIs, since they are on different thread(s) than the call stack? I'd imagine this is the same for the Node.js APIs. They would use C++ and their own threads. https://www.youtube.com/watch?v=8aGhZQkoFbQ – Cazineer May 10 '18 at 19:22
  • The native code is allowed to do things that your Javascript is not. It is implementation specific though as to what approach it takes and is often considered a black box. The NodeJS api is different than the web api since it has to supply an API for writing applications instead of just web apps. A notable difference that stood out to me is the NodeJS exposes async methods while I cannot think of a web api that is not synch. – Deadron May 11 '18 at 16:24