简体   繁体   中英

Resolving a promise not working as expected

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) }

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)

} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM