Search code examples
javascriptparse-platformpromisechaining

JavaScript Promises


Im trying to understand promises, but Im hitting a roadblock, I'm trying to query my Parse database for the last ran date object so that ill know when it was ran last. Then pass that date to the next function who can check my movie database for anything after the last time it was called. (I'm doing this to send out push notifications for new fields manually entered into Parse class) then actually send the push. But I'm not understanding the .then and promises, I'm new to JavaScript so any help would be appreciated!

Here is my code i have now.

Parse.Cloud.job("TestSendNewMoviePush", function(request, response) {
    var query = new Parse.Query("MovieStatus");
    var lastRunDateQuery = new Parse.Query("LastRun");
    var lastRunDate;
    var newDate;
    var newCount = 0;
    var installQuery = new Parse.Query(Parse.Installation);
    query.greaterThan("updatedAt", lastRunDate);
    query.equalTo("CurrentStatus", "Ready");
    query.equalTo("imageStatusName", "Green");
    installQuery.equalTo("role", "downloader");

    lastRunDateQuery.get("d3WeNEwzIu", {
    success: function(lastDateRanObj) {
    console.log("Got the object " + lastDateRanObj);
    var date = new lastDateRanObj.updatedAt;
    lastRunDate = lastDateRanObj.updatedAt;
    console.log(lastRunDate);
    return lastRunDate;
    },
    error: function(lastDateRanObj, error) {
    console.log("Failed to get object");
  }
}).then(
  query.count({
    success: function(count) {
      newCount = count;
      return newCount

    }, 
    error: function(e) {
    }
  })).then(

  Parse.Push.send({
        where: installQuery,
        data: { 
  "alert": newCount + " new movie(s) available!",
  "badge": "Increment"
}
    }, {
    success: function() {
      response.success("Success");
    },
    error: function(e) {
      response.error("Error:" + e.code);
    }
    }));
});

Solution

  • lastRunDateQuery.get() returns a Promise object, which you can chain with a then, which itself is a function taking 2 functions as arguments: one that is called if the promise is resolved, and one that is called if the promise is rejected. You use these instead of the success and error parameters:

    lastRunDateQuery.get()
        .then(function(data) {
           // success!!
        }, function(error) {
           // error :(
        });
    

    The functions you passed as arguments to then can themselves return promises, which you may subsequently chain with a then. In the example below I have omitted the error callbacks:

    lastRunDateQuery.get()
        .then(function(data) {
           // data is the result of lastRunDateQuery.get()
           return query.count();
        })
        .then(function(data) {
           // data is the result of query.count()
           return someOtherThing.someOtherMethodReturningAPromise();
        });
        .then(function(data) {
          // data is the result of someOtherThing.someOtherMethodReturningAPromise()
        });
    

    And so on.

    I would recommend having a look at the Promises/A+ spec - it's very instructive.

    EDIT:

    If the chaining concept is a bit confusing just think of it as a shorthand for the following:

    var aPromise = lastRunDateQuery.get();
    aPromise.then(
        function() {}, // promise was resolved -> call this function
        function() {}, // promise was rejected -> call this function
    );