JavaScript Promise Chaining-为什么不工作?

时间:2017-07-28 21:14:43

标签: javascript node.js es6-promise

在下面的代码中,有人可以解释为什么在Promise链中调用secondMethod有效,但调用secondMethod()却没有?

function firstMethod() {
    return new Promise(function(resolve, reject){
        setTimeout(function() {
            console.log('first method completed');
            resolve();
        }, 2000);
    });
};


function secondMethod() {
    return new Promise(function(resolve, reject){
        setTimeout(function() {
            console.log('second method completed');
            resolve();
        }, 2000);
    });
};

function thirdMethod() {
    return new Promise(function(resolve, reject){
        setTimeout(function() {
            console.log('third method completed');
            resolve();
        }, 3000);
    });
};

// Works
firstMethod().then(secondMethod).then(thirdMethod);

// Doesn't work - executes secondMethod immediately after firstMethod
// firstMethod().then(secondMethod()).then(thirdMethod);

2 个答案:

答案 0 :(得分:3)

第二种方法不起作用,因为您在任何超时解决之前以同步方式立即调用函数。

这是另一种思考正在发生的事情的方式:

// you're calling all your methods and creating promises before creating the chain
let first = firstMethod();
let second = secondMethod();
let third = thirdMethod();

first.then(second).then(third);

答案 1 :(得分:1)

因为Promise.then需要一两次回调。它没有承诺。

当您立即致电secondMethod时,您将承诺传递给.then

它基本上与这样做相同:

firstMethod()
  .then(new Promise(...)) // Should be a function, not a Promise