gpt4 book ai didi

javascript - 解决未按预期工作的 promise

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

我想在 updateGuider 函数解析后使用 async/await 运行 console.log('Procccess Ends');..

类似于下面的代码:

tutor();

async function tutor(){
console.log('tutor function initiated..');
// wait until updateGuider function resolves
await updateGuider('default');
// The expected result is to reach this line after updateGuider resolves, but we can't so far!
console.log('Procccess Ends');


}

function updateGuider(state){
return new Promise((resolve) => {

if(state == 'done'){
console.log('updateGuider has been resolved!');
resolve();
}

switch(state) {
case 'default':
speak();
break;
}

});
}


async function speak(){

setTimeout(function(){
//after 5 seconds we resolve the updateGuider from speak function
updateGuider('done')
},5000)

}

但即使我们解析了 updateGuider,它也不会运行 console.log('Procccess Ends');

我错过了什么以及如何解决这个问题?

如何从 speak 解析 updateGuider

更新:感谢@h2ooooooo这段代码可以工作,但我不明白它是如何工作的,如果这是一个好的解决方案以及它是如何工作的,请帮我一下!

tutor();

async function tutor(){
console.log('tutor function initiated..');
// wait until updateGuider function resolves
await updateGuider('default');
// The expected result is to reach this line after updateGuider resolves, but we can't so far!
console.log('Procccess Ends');


}

function updateGuider(state){
return new Promise((resolve) => {

switch(state) {
case 'default':
speak(resolve);
break;
}

});
}


async function speak(resolve){

setTimeout(function(){
//after 5 seconds we resolve the updateGuider from speak function
console.log('entered speak')
resolve();
},5000)

}

最佳答案

每次调用 updateGuider 时,您都会返回不同的 promise 。严格来说,你不能像这样解析 updaterGuide 。此外,除非您在异步函数中等待某些内容,否则它不会执行任何操作,因此目前没有理由异步。这并不完美,但您已经了解了问题的要点。


function updateGuider(state){
return new Promise((resolve) => {

if(state == 'done'){
console.log('updateGuider has been resolved!');
resolve();
}

switch(state) {
case 'default':
speak(resolve);
break;
}

});
}

function speak(resolve){

setTimeout(function(){
//after 5 seconds we resolve the updateGuider from speak function
resolve()
},5000)

}

关于javascript - 解决未按预期工作的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59671412/

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