Search code examples
javascriptparse-platformpromiseparse-cloud-code

Parse.com/CloudCode Promises not quite clear


I'm stuck with this Problem and couldn't find an answer. I wrote the following Function in Cloud Code.

function getSoccerData() 
{
    console.log("Entering getSoccerData");
    var promise = Parse.Cloud.httpRequest({
        url: 'http://www.openligadb.de/api/getmatchdata/bl1/2015/'
    }).then(function(httpResponse) {
        console.log("Just a Log: " + JSON.parse(httpResponse.buffer)[1].Team1.TeamName);
        return JSON.parse(httpResponse.buffer);
    });
    return promise;
}

I hope I did use Promises the right way here.

Now I assign the function to a variable in my background job like this.

Parse.Cloud.job("updateSoccerData2", function (request, response) {

    var matchArray 
    matchArray = getSoccerData().then(function() {
        console.log("TestLog: " + matchArray[1].Team1.TeamName);
        response.success("Success!");
    }, function(error) {
        response.error(error.message);
    });
});

When I try to run this I get the following Log output

E2016-01-28T16:28:55.501Z]v412 Ran job updateSoccerData2 with:
Input: {} Result: TypeError: Cannot read property 'Team1' of undefined at e. (_other/nunutest.js:28:48) at e.i (Parse.js:14:27703) at e.a.value (Parse.js:14:27063) at e.i (Parse.js:14:27830) at e.a.value (Parse.js:14:27063) at Object. (:846:17) I2016-01-28T16:28:55.561Z]Entering getSoccerData I2016-01-28T16:28:56.920Z]Just a Log: SV Darmstadt 98

So the it seems that the asynchronous function ist not ready when the assignment is made. Can anybody help? Thank you!


Solution

  • Your function looks ok, but the job needs to change to:

    Parse.Cloud.job("updateSoccerData2", function (request, response) {
        getSoccerData().then(function(matchArray) {
            console.log("TestLog: " + matchArray[1].Team1.TeamName);
            response.success("Success!");
        }, function(error) {
            response.error(error.message);
        });
    });
    

    because the function returns a promise that you wait for and the end result of that promise is your array of data.