javascript - 为什么 console.log() 在 Promises 的resolve() 函数中立即执行?

标签 javascript promise

以下面为例:

function sayHello () {
  return new Promise( function(resolve, reject) {
    console.log('Were inside the promise');

    return resolve(5);
  })
}

sayHello().then(function(success){
  console.log(success)
})

console.log('Im outside the promise')

我们知道它按以下顺序执行:

Were inside the promise
Im outside the promise
5

然后,对于类似的事情:

function sayHello () {
  return new Promise( function(resolve, reject) {
    console.log('Were inside the promise');

    return resolve((function(){
      return 5
    })());
  })
}

sayHello().then(function(success){
  console.log(success)
})

console.log('Im outside the promise')

它返回与前一个示例相同的 console.log 输出序列。太棒了,有道理;无论resolve中的值是什么,当then()执行时,都会作为参数通过管道传输。

为什么,当我有类似下面的内容时:

function sayHello () {
  return new Promise( function(resolve, reject) {
    console.log('Were inside the promise');

    return resolve(console.log(5));
  })
}

sayHello().then(function(success){
  console.log(success)
})

console.log('Im outside the promise')

我收到这个订单了吗:

Were inside the promise
5
Im outside the promise

最佳答案

当解析器函数在下一个“tick”中被调用时,它的参数会立即被评估。这就是为什么您会在第三个代码段示例中看到 console.log(5)before then 回调执行。如果您将第二个代码片段更改为:

function sayHello() {
  return new Promise(function(resolve, reject) {
    console.log('Were inside the promise');
    return resolve((function() {
      console.log('Inside resolver argument');
      return 5
    })());
  })
}
sayHello().then(function(success) {
  console.log(success)
});
console.log('Im outside the promise');

关于javascript - 为什么 console.log() 在 Promises 的resolve() 函数中立即执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49916466/

相关文章:

javascript - 如何在 JavaScript 中使用 API key ?

javascript - 当用户离开页面时如何通知服务器?

javascript - 当数据位于数组中时更改 setState 中的值

javascript - 如何在现有对象中创建 javascript 对象

javascript - 使用 Q (promise) 的 Node.js 上的变量上下文问题

javascript - 如何从 Promise 返回值并在另一个方法中使用它?

javascript - 我应该封装我的 javascript 库吗?

javascript - Promise 构造函数是必要的还是可以避免?

node.js - ffprobe 无法读取 AWS 上 Node JS createWriteStream() 生成的文件

javascript - 带有对象/原型(prototype)的链式 Promise(Q 延迟)