gpt4 book ai didi

javascript - Javascript Promise 如何与 setTimeOut 配合使用

转载 作者:行者123 更新时间:2023-12-02 17:58:25 26 4
gpt4 key购买 nike

如果这是一个基本问题,我深表歉意。我真的很困惑 Promise 在 Javascript 中是如何工作的。

我有以下代码:

function wait(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Done waiting");
resolve(ms);
}, ms);
});
}

let a = true;

let p = new Promise(async (resolve, reject) => {
await wait(3000);
console.log("Inside Promise");
if (a) {
resolve("Success");
} else {
reject("Failure");
}
});

const func = async () => {
let output = await p;
console.log(output);
};

func().then(console.log("abc"));

这是打印输出:

abc
Done waiting
Inside Promise
Success

我一生都无法弄清楚为什么abc首先打印。难道不应该等待 func() 执行完成吗?我预计abc最后打印。谁能引导我完成执行步骤?提前致谢。我真的很感激。

最佳答案

您提供给 Promise.then 的不是回调,它会在运行时立即评估。您需要将 console.log 移至函数的 body 中:

func().then(() => console.log("abc"));

请参阅下面的工作示例:

function wait(ms) {
return new Promise((resolve, reject) => {
setTimeout(() => {
console.log("Done waiting");
resolve(ms);
}, ms);
});
}

let a = true;

let p = new Promise(async (resolve, reject) => {
await wait(3000);
console.log("Inside Promise");
if (a) {
resolve("Success");
} else {
reject("Failure");
}
});

const func = async () => {
let output = await p;
console.log(output);
};

func().then(() => console.log("abc"));

关于javascript - Javascript Promise 如何与 setTimeOut 配合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75067681/

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