为什么 Promise 中的代码是同步执行的? [英] Why code in Promise executes synchronously?

查看:37
本文介绍了为什么 Promise 中的代码是同步执行的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中我有一个很长时间运行的操作,所以我决定把它放在一个Promise中,因为我认为这样我可以继续执行其他操作,而里面的代码Promise 正在运行.

In my project I have a very long running operation, so I decided to put it in a Promise because I thought that in this way I could continue to execute the other operations while the code inside the Promise was running.

调试时发现Promise外的代码只有在Promise内的代码执行完毕后才会执行.

While debugging, I find out that the code outside the Promise executed only when the code inside the Promise finished executing.

下面是我在做什么在我的项目为例(它模拟一个长时间的操作,所以它需要一段时间):

Here is an example of what I'm doing in my project (it simulates a long operation, so it takes a while):

new Promise(function(resolve, reject) {
  var i = 0;
  while (i < 1000000000) {
    i++
  }
  console.log("Executing inside Promise");
});

console.log("Executing outside Promise");

我不确定为什么会发生这种情况,这就是我问它的原因.但我认为这与 Promise 中的代码是同步的这一事实有某种关系.实际上,当它是异步的(即 setTimeout() 方法)时,它会在外部代码执行完毕后运行.

I am not really sure why this is happening and that's why I asked it. But I think that it is somehow related to the fact that the code inside the Promise is synchronous. Indeed when it is async (i.e. the setTimeout() method) it runs after the outside code finishes executing.

new Promise(function(resolve, reject) {
  setTimeout(function() {
    var i = 0;
    while (i < 1000000000) {
      i++
    }
    console.log("Executing inside Promise");
  }, 3000)
});

console.log("Executing outside Promise");

但是我还是不明白为什么Promise里面的代码是同步执行的?不应该异步执行吗?

But I still can't figure out why the code inside the Promise is executing synchronously? Shouldn't it execute asynchronously?

推荐答案

无极构造中的代码是为了同步运行.这样做的一个原因是它允许您执行以下操作:

The code inside the Promise constructor is meant to run synchronously. A reason for this is that it allows you to do:

var resolve, reject
var p = new Promise(function (res, rej) { resolve = res; reject = rej })
// you can return this `p` from a function or use it with p.then()
// then later
resolve(value)

请注意,像您的 for 循环这样的长时间运行的代码总是阻塞,即使您在 setTimeout 中运行它.如果您在超时时间内运行它,它只会在不同的时间阻止其他所有内容.Promises 的异步部分对于网络请求等需要等待结果的 I/O 事情很有用.for 循环不需要等待,实际上它在工作中非常非常辛苦:).如果您需要并行运行昂贵的代码,则必须使用类似 Web Workers 在浏览器或新的 node.js 中的 worker_threads API.

Note that long running code like your for loop is always blocking, even if you run it inside a setTimeout. If you run it in a timeout it will just block everything else at a different time. The asynchronous part of Promises is useful for I/O things like network request, which require waiting for a result. That for loop doesn't require waiting, in fact it's very very hard at work :). If you need to run expensive code in parallel, you have to use something like Web Workers in the browser or the new worker_threads API in Node.js.

这篇关于为什么 Promise 中的代码是同步执行的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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