Reputation: 3543
I want to use async / await to run console.log('Procccess Ends');
after updateGuider
function resolves..
Something like the code below:
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)
}
But even though we resolve the updateGuider
it won't run the console.log('Procccess Ends');
What I miss and how to fix this?
How can I resolve updateGuider
from speak
?
UPDATE: Thanks to @h2ooooooo This code works but I can't understand how it works could you please give me a hand if it's a good solution and how it works!
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)
}
Upvotes: 0
Views: 50
Reputation: 217
you are returning different promises each time you call updateGuider. Strictly speaking, you cannot resolve updaterGuide like this. Also unless you await something in an async function it does nothing, so speak has currently no reason to be async. This is not perfect, but you get the gist of the problem.
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)
}
Upvotes: 2