gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:28:11 24 4
gpt4 key购买 nike

我尝试按此顺序调用函数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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com