Ad

Meteor.js - How To Check Values From Asynchronous Callback

CONTEXT

Im making a call which, if successful, changes the value of a boolean from false to true. Then, outside of this call, I check if this boolean is true and, if so, I route to another page.

PROBLEM

Console logs indicate that the if statement which checks the boolean's value is being executed before the calls have had a time to change the boolean's value. I realize that this is because of asynchronicity, but not sure what the correct design pattern for this would be. Here is a snippet:

     //set variables to check if the even and user get updated or if error
    var eventUpdated = false;

     Meteor.call('updateEvent', eventId, eventParams, function(error, result){
      if(error){
        toastr.error(error.reason)
      } else {
        var venueId = result;
        toastr.success('Event Info Updated');  
        eventUpdated = true;

        console.log(eventUpdated)
      }               
    });

    console.log(eventUpdated)


     if (eventUpdated) {
         Router.go('/get-started/confirmation');
     }

POSSIBLE SOLUTIONS

I'm guessing I need a way to hold the if statement from being executed until the callback returns a value. Based on Googling, I think this has something to do with this but not too clear on how to actually use it.

Ad

Answer

Since the conditional is run before the callbacks have returned a value, you need a conditional that is inside a function that is being run reactively. I used the following code:

    Tracker.autorun(function(){
        if (Session.get('userUpdated') && Session.get('passwordUpdated') && Session.get('eventUpdated')) {
            Router.go('/get-started/confirmation');
        }
    });

You can read more about Meteor reactivity here.

Ad
source: stackoverflow.com
Ad