将函数包装在promise中是否会导致该函数的代码被另一个线程并行执行? [英] Does wrapping a function in a promise cause the function's code to be executed in parallel by another thread?

查看:23
本文介绍了将函数包装在promise中是否会导致该函数的代码被另一个线程并行执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了许多有关Promise和async/await的文章.它们似乎都处理返回承诺的API以及如何使用这些承诺.我还是有些困惑.

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.

可以说我有一个包含三(3)个循环的函数.假设地,每个循环执行一些工作需要五(5)秒才能完成,将每次迭代的结果推入该循环的数组中.这项工作是同步进行的(循环1运行,然后是循环2,然后是循环3).

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).

然后函数在返回之前对所有三个循环的结果进行处理.假设的总执行时间约为十六(16)秒.

The function then does something with the results of all three loops before returning. The total hypothetical execution time is around sixteen (16) seconds.

如果将循环放入自己的函数中,则包装在一个promise中,然后使用 await Promise.all async函数中等待(在对结果进行处理之前),它们是否会并行执行(因为它们是在事件循环中,而不是在调用堆栈中),并且一旦所有三(3)个承诺都解决了,函数将继续执行吗?这比同步的整个过程快吗?

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?

我想我何时/为什么要通过同步JS创建自己的Promise感到困惑?

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
}

推荐答案

JavaScript执行是单线程的.这意味着,如果不使用诸如WebWorker之类的机制,则所有javascript代码都不会并行执行.有了这样的说法,有一些原因可以使用诸如promises之类的异步代码来执行同步javascript.

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. 您的代码需要一段时间才能执行.

JavaScript执行与浏览器中的UI共享相同的线程.这意味着,如果您的代码需要5秒钟才能执行,则用户浏览器将在此期间被阻止.您可以改为将执行分为多个异步执行的块,这将使UI保持响应状态.

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. 您正在从现有的异步函数中参与Promise链.

有时需要混合异步和同步代码.Promise允许您将异步和同步代码组合到一个执行链中,而不必具有硬编码的依赖项.

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. 您正在遇到堆栈大小限制.

根据代码和库的编写方式,有时您可能会耗尽堆栈,这可能导致堆栈大小异常或仅占用过多的内存.通过异步执行一段代码,它获得了自己的新堆栈.

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 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.

这篇关于将函数包装在promise中是否会导致该函数的代码被另一个线程并行执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆