ericaddison / Hailing_Frequencies

Final Project for UT Advanced Programming Tools
0 stars 0 forks source link

Handling async functions #18

Open psigourney opened 6 years ago

psigourney commented 6 years ago

Was just able to get Promises in javascript working. It's a way to ensure that one function fully completes (like making an ajax call wait for the results to arrive) before the next function runs. Kinda like a callback but not really. You basically encapsulate your first function contents with a Promise function.

 function myFirstFunc () {
    return new Promise(function(resolve, reject){  //<<<< Add this line
        normal firstFunc stuff;
        if(firstFuncWorked){
               resolve();
        }
        else{
                reject();
         }
    }
  }

Now when you call myFirstFunc, you can add a .then to the end to have a second function called once resolve() is reached in your first function (if reject() is reached, the .then part doesn't trigger):

    myFirstFunc().then(function(){
         secondFunctionStuff goes here;
    });

I used this in the FirebaseHeader file so whenever firebase.auth().onAuthStateChanged() triggers and the Firebase user is refreshed, it will call another function to retrieve the corresponding local user account from the ndb database.

**Caveat**: IE doesn't support Promises (Chrome, FF, Safari all do though).