Are JS Promises, processor-like parallelism?

前端 未结 2 837
有刺的猬
有刺的猬 2021-01-27 19:38

I was reading about the JS Promises and since they are generally

extremely useful for async success/failure, because you\'re less interested in the exact

相关标签:
2条回答
  • 2021-01-27 19:47

    Promises really has nothing to do with processor parallelism. Promises are a software concept that lives many, many levels above the processor. In Javascript, it would be the Javascript run-time engine that would or would not take advantage of how processors can run certain things in parallel and an implementation of promises many levels above that would not influence that in any way.

    Promises are a software architecture for keeping track of asynchronous activities, registering an interest in their completion (or failure), and coordinating those asynchronous activities with other activities. The use of asynchronous activities allows the system to have more than one activity "in-flight" at the same time (such as downloading an image while also waiting for the response to an ajax call while also responding to user events). But, this ability to use asynchronous activities is not unique to promises and is not related to processor parallelism.

    Promises do not, by themselves, break any task up into a parallel actions. If you break your own task up into multiple asynchronous pieces, then promises allow you to manage those asynchronous activities and results in a structured way.

    0 讨论(0)
  • 2021-01-27 19:58

    No, this is not parallel processing as promises can be on a single thread and there is no concept of task parallelization built into them, they arent going to break a problem down into parallel subtasks etc. They are solely a method to respond to and manage asynchronous events.

    The best mock I could think of to mimic parallelism would require the user to break their problem down into parallizable tasks and then pass each call to a Promise.All type function which would use webworkers to handle the invocations. Most likely a useless exercise as you are basically just decorating webworkers with promises. You'd be much better advised to leverage a library like parallel.js in cases like this.

    0 讨论(0)
提交回复
热议问题