我尝试按此顺序调用函数call2(),然后调用call3(),以便仅在call2() 终止时调用call3()。我正在使用 Promise 来实现这一目标。
但是 call3() 在 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());
我显然做错了什么,或者无法理解如何使用 Promise。请问有什么帮助吗?
最佳答案
在 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);
关于node.js - nodejs - 使用 Promise 终止前一个函数后按顺序调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41767611/