gpt4 book ai didi

带有等待解释的 Javascript Promise

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:57:49 24 4
gpt4 key购买 nike

我只想了解 promises 和 await 是如何协同工作的。看下面的代码:

console.log("One: Started");
setTimeout(function(){console.log("One: Completed")}, 1000);
console.log("Two: Started");
setTimeout(function(){console.log("Two: Completed")}, 2000);
console.log("Three: Started");
setTimeout(function(){console.log("Three: Completed")}, 3000);

所以这当然是日志:

One: Started
Two: Started
Three: Started
One: Completed
Two: Completed
Three: Completed

我想在下一个开始之前完成一个。我根据对 promises 和 await 的理解写了这篇文章,但这不起作用。请有人尝试编辑此代码以使其正常工作。 请解释一下,因为我正在尝试理解 promises 和 await

async function LogAll() {
console.log("One: Started");
await function() {
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log("One: Completed");
resolve();
}, 1000);
});
}
console.log("Two: Started");
await function() {
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log("Two: Completed");
resolve();
}, 2000);
});
}
console.log("Three: Started");
await function() {
return new Promise((resolve, reject) => {
setTimeout(function(){
console.log("Three: Completed");
resolve();
}, 3000);
});
}
}

LogAll();

最佳答案

您需要await promises,而不仅仅是函数。当您await function ...(不调用它)时,该函数被评估为一个表达式,然后被丢弃。只需调用函数:

async function LogAll() {
console.log("One: Started");
await (function() {
return new Promise((resolve, reject) => {
setTimeout(function() {
console.log("One: Completed");
resolve();
}, 1000);
});
})();
console.log("Two: Started");
await (function() {
return new Promise((resolve, reject) => {
setTimeout(function() {
console.log("Two: Completed");
resolve();
}, 2000);
});
})();
console.log("Three: Started");
await (function() {
return new Promise((resolve, reject) => {
setTimeout(function() {
console.log("Three: Completed");
resolve();
}, 3000);
});
})();
}

LogAll();

或者,对于这个例子,根本不使用函数——直接等待 promise:

async function LogAll() {
console.log("One: Started");
await new Promise((resolve, reject) => {
setTimeout(function() {
console.log("One: Completed");
resolve();
}, 1000);
});
console.log("Two: Started");
await new Promise((resolve, reject) => {
setTimeout(function() {
console.log("Two: Completed");
resolve();
}, 2000);
});
console.log("Three: Started");
await new Promise((resolve, reject) => {
setTimeout(function() {
console.log("Three: Completed");
resolve();
}, 3000);
});
}

LogAll();

关于带有等待解释的 Javascript Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50326040/

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