MMrj MMrj - 3 months ago 9
Javascript Question

Meteor can't exit method

I'm not being able to exit a method when returning an alert. For example i have here two validations "hasEventWithExternalId" and "isValidFacebookEvent",if i try the same event more than once the result of "hasEventWithExternalId" turns true and it returns the alert, but then the execution of the method continues and creates a new event and returns the success alert. Any ideas on wahts happening?

Template.eventnew.events({
'click #btn-event-data': function(e) {
//Check if facebook event was already imported
Meteor.call('hasEventWithExternalId', id, function(error, result) {
if(result){
return swal({
title: "Event already imported from Facebook",
text: "That facebook event was already imported to this application",
showConfirmButton: true,
type: "error"
});
}

});

//Check if it is a valid facebook event
Meteor.call('isValidFacebookEvent', id, function(error, result) {
if(!result){
return swal({
title: "Invalid Facebook event",
text: "That's not a valid facebook event'",
showConfirmButton: true,
type: "error"
});
}
});

Meteor.call('importEventFromFacebook', id, function(error, result) {
if(error){
console.log(error);
return false;
}
else{
return swal({
title: "Event sucessfully imported",
showConfirmButton: true,
type: "success"
});
}
});

}


One of the methods:

Meteor.methods({

//Check if Event with external id x already exists
hasEventWithExternalId: function(externalId){
if(Event.find({externalId: externalId}).count()>0)
return true;
else
return false;

}
});

Answer

Actually you are executing your 3 Meteor.call() no matter what is the result of your 2 checks.

Therefore, even if your "hasEventWithExternalId" call returns true (i.e. it could find an event already imported, like the 2nd time you fire your button click event), your other calls will still be executed, in particular your "importEventFromFacebook" call that will try to (re-)import your FB event.

You should perform your next Meteor.call() only if the previous one did not return an error / result that say not to continue, e.g. in an else block.

For example:

  Meteor.call('hasEventWithExternalId', id, function(error, result) {
      if (error) return;

      if (result){
          return swal({
                title: "Event already imported from Facebook",
                text: "That facebook event was already imported to this application",
                showConfirmButton: true,
                type: "error"
            });
      } else {
          Meteor.call('isValidFacebookEvent', id, function (error, result {
              // etc.
          });
      }

  });

But in the first place, why not doing all this directly server-side, in a single Meteor.methods(), instead of having to execute 3 different calls?

Comments