0

have got a provider async function that creates a new user using angularfire2/auth...I have been tracking the progress with console logs as chrome doesn't work in promises very well (or I can't get it to work) and found that I am going into the "then" component of the promise and getting a uid so the user is being created. However I then call another async function (from within the "then" function) that creates a profile object on the database but this function never gets called...don't know what happens.

I find that the promised is not all that's promised...has anyone got an example of running a promise after a promise?

Each function works well on it's own, just not combined.

I had thought of adding it to the calling function of the button click event but as the log has shown me, the function returns before the 'then' completes.

Is there any way of blocking the promise or of stopping the function from returning until the promise has been completed. I have tried the async/ await on the function with the same problem.

SuperRoo
  • 87
  • 1
  • 7

1 Answers1

0

I completely stuffed it up...yes the promise provides a return function for the completed/error (promise.then(completed).catch(error)) but each promise is again asynchronous...so they can be called in any order and the calling function will probably finish before the functions return...hence the async/await commands...I love Mostafa Gaafar for his article on this. Basically:

async buttonClick(){
  let errMsg = '' as string;
  await myService.myFunction.then(ret =>{
    //ret is a string return with any error message...no messages then all 
     ok
      errMsg = ret;
   }).catch{e => {
      errMsg = e.message;
   }); //EO service function
   //if you have an error then do something else do something else
 } //EO buttonClick

with

async myService.myFunction(): Promise<string>{
 let errMsg = '' as string;
 let data1 = '' as string;
 await Promise1.then((data) =>{
     //first run
     data1.value;
  }).catch( e=>{
     errMsg = e.message;
  });
  if(errMsg == ''){
     //no errors so far
     await Promise2.then((data) =>{
        //second run
        //Do something
      }).catch( e=>{
         errMsg = e.message;
      });
  } //eo if
  return errMsg;
}

This will all complete synchronously...

  • button click called
  • service function run
  • promise1 run and completed
  • promise2 run and completed
  • service function exit
  • button click exit

You can use Try/Catch wrappers as well to return an error message. Have tested this and all works well with AngularFire2 ...let me know if I have forgotten something.

  • Angular/cli: 1.2.6
  • node: 6.9.4
  • Ionic: 3.7.0
SuperRoo
  • 87
  • 1
  • 7