Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

javascript - Does wrapping a function in a promise cause the function's code to be executed in parallel by another thread?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...