我想在console.log('Procccess Ends');
函数解析后使用异步/等待来运行updateGuider
。
类似于以下代码:
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');
我想念什么以及如何解决?
如何从updateGuider
解析speak
?
更新:感谢@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)
}
答案 0 :(得分:2)
每次调用updateGuider时,您将返回不同的承诺。严格来说,您无法像这样解决updaterGuide。另外,除非您等待异步函数中的某些操作,否则它什么也不做,因此,speak当前没有理由进行异步。这不是完美的方法,但是您可以找到问题的要点。
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)
}