Sara Ree
Sara Ree

Reputation: 3543

resolving a promise inside a function from another function

I want to resolve the updateGuider function from speak function like this:

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');


}
// Not working unless we use var instead of let?!
let updateGuiderResolve;

function updateGuider(state){    
  return new Promise((resolve) => { 
  updateGuiderResolve = resolve;
    switch(state) {
          case 'default':
          speak();
          break;         
    }
    
    });  
}


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

As you can see the code doesn't work (Expected result is to see console.log('Procccess Ends') after 5 seconds);

I noticed that if I change the let updateGuiderResolve to var updateGuiderResolve everything works fine! Why?

Upvotes: 0

Views: 417

Answers (1)

Bergi
Bergi

Reputation: 664195

The problem with let is (as the error message should explain) that you are trying to use the variable before it has been initialised: you are calling tutor() above the let updateGuiderResolve; declaration.

But really you shouldn't need this global/static shared variable for the resolver function at all. Instead, make speak create and return the promise itself:

async function tutor() {
  console.log('tutor function initiated..');
  await updateGuider('default');
  console.log('Procccess Ends');
}

async function updateGuider(state) {
  switch(state) {
     case 'default':
       return speak();   
  }
}

function speak() {
  console.log('entered speak')
  return new Promise(function(resolve) {
    setTimeout(resolve, 5000);
  });
}

tutor().catch(console.error);

Upvotes: 2

Related Questions