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

时间:2018-04-19 08:38:42

标签: 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输出序列。很棒,很有意义;无论解决方案中的值是什么,都会在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

2 个答案:

答案 0 :(得分:2)

在下一个'tick'中调用解析器函数时,会立即计算其参数。这就是为什么您在第三个代码段示例中看到console.log(5)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');

答案 1 :(得分:0)

documentation of Promise constructor解释说:

  

语法

new Promise( /* executor */ function(resolve, reject) { ... } );
     

参数

     

executor

     
    

使用参数resolve和reject传递的函数。执行器函数由Promise实现立即执行,传递resolvereject函数(在executor构造函数甚至返回创建的对象之前调用Promise )。 [...]
    执行程序通常启动一些异步工作,然后,一旦完成,调用resolve函数来解析promise或者如果发生错误则拒绝它。 [...]
    执行程序的返回值将被忽略。

  

根据上面公开的知识,您的代码应该是:

function sayHello () {
  return new Promise(function(resolve, reject) {
    // Start an asynchronous operation
    // This example uses setTimeout() to simulate a lengthy operation (1 second)
    // but in a real program you probably start a network request, 
    // a database operation or a file system operation
    setTimeout(function() {
        // This is when the async operation completes
        console.log('Were inside the promise');
        // Fulfill the promise, set '5' as the value returned by the promise
        resolve(5);
    }, 1000);
  });
}


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

console.log('Im outside the promise');