Javascript 将函数传递给Promise.then会导致与传递嵌套函数不同的行为

Javascript 将函数传递给Promise.then会导致与传递嵌套函数不同的行为,javascript,asynchronous,promise,es6-promise,Javascript,Asynchronous,Promise,Es6 Promise,下面的代码 function doSomething(msg){ return new Promise((resolve, reject) => { setTimeout( () => { console.log(msg); resolve(); }, 2000); }) } let start = Date.now(); let end; doSome

下面的代码

function doSomething(msg){ 
    return new Promise((resolve, reject) => {
      setTimeout(
        () => {
          console.log(msg);
          resolve();
        }, 
        2000);
    }) 
}

let start = Date.now();  
let end;  
doSomething("1st Call")
  .then(()=>doSomething("2nd Call"))
  .then(()=>doSomething("3rd Call"))
  .then(()=>{
    end = Date.now();
    console.log('start',start);
    console.log('end',end);
    console.log('elapsed time',end-start);
  }) 
按预期打印第一次呼叫、第二次呼叫和第三次呼叫,每个console.log语句之间间隔2秒

但是,如果我从then块中删除箭头函数,行为将完全不同,即

doSomething("1st Call")
  .then(doSomething("2nd Call"))
  .then(doSomething("3rd Call"))
  .then(()=>{
    end = Date.now();
    console.log('start',start);
    console.log('end',end);
    console.log('elapsed time',end-start);
  }) 
有了这段代码,所有console.log语句都会同时打印,所用时间仅为2秒,而不是每个函数2秒(在第一个示例中总共6秒)

换句话说,为了使代码正常工作,then函数需要接受一个函数(本例中的箭头),然后从该函数内部,我可以执行进一步的函数调用

为什么我不能直接传递函数,为什么它需要嵌套在另一个函数中?

.then()
需要一个回调函数,当调用
Promise
函数时,该函数将被调用。then()
函数将被调用

当你这么做的时候

.then(doSomething("2nd Call"))
不再注册稍后调用的回调函数,而是立即调用
doSomething()

您可以将对函数的引用传递给
。然后()
函数和
。然后()
将在
承诺履行时调用该函数

.then(doSomething)
但是您将无法将任何参数传递给
doSomething
函数

。然后(doSomething(“第二次调用”)
仅在
doSomething
返回函数时才起作用。在这种情况下,返回的函数将注册为回调函数,并在
Promise
实现时调用

您可以使用
.bind()
函数来获取一个函数,该函数将用作
.then()
函数的回调

函数doSomething(msg){
返回新承诺((解决、拒绝)=>{
设置超时(()=>{
控制台日志(msg);
解决();
}, 2000);
}); 
}
让我们开始=Date.now();
让我们结束;
doSomething(“第一次呼叫”)
.then(doSomething.bind(null,'2nd Call'))
.then(doSomething.bind(null,'3rd Call'))
.然后(()=>{
end=Date.now();
console.log('start',start);
console.log('end',end);
console.log('经过的时间',结束-开始);
})
如果使用
然后(fn())
,它将不会为下一个
返回值。然后(…)
使用,因此它可以立即继续

使用
.then(variable=>fn())
时,下一个
。然后(…)
将等待第一个解决或拒绝

这类似于函数之间的差异

function a () {
   stuff
}

function b (){
  return stuff
}