nodejs - 使用Promise终止前一个函数后按顺序调用函数

时间:2017-01-20 15:53:43

标签: node.js promise

我试图调用函数call2()然后按顺序调用3(),这样只有当call2()终止时才调用call3()。我正在使用Promise来实现这一目标。

但是call2()在call2()终止之前被调用。这是我的代码:

function call2() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log("calling 2");
            resolve(true);
        }, 3000);
    });
}

function call3() {
    console.log("calling 3");    
}

call2().then(call3());

我显然做错了什么,或者无法理解如何使用诺言。有什么帮助吗?

2 个答案:

答案 0 :(得分:3)

then(call3())中,您正在调用 call3 函数而不是将其作为回调传递,请更改为:

call2().then(call3);



function call2() {
   console.log('Start...');
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            console.log("calling 2");
            resolve(true);
        }, 3000);
    });
}

function call3() {
    console.log("calling 3");    
}

call2().then(call3);




答案 1 :(得分:0)

你必须将你的call3包装到函数中:

call2().then(()=>call3());