Does Wrapping A Function In A Promise Cause The Function's Code To Be Executed In Parallel By Another Thread?
Solution 1:
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.
- 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.
- 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.
- 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.
- 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.
Post a Comment for "Does Wrapping A Function In A Promise Cause The Function's Code To Be Executed In Parallel By Another Thread?"