Parse.com/CloudCode 承诺不太清楚

Parse.com/CloudCode Promises not quite clear

我被这个问题困住了,找不到答案。我在 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;
}

我希望我在这里正确使用了 Promises。

现在我将函数分配给后台作业中的一个变量,就像这样。

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);
    });
});

当我尝试 运行 时,我得到以下日志输出

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

所以似乎在进行赋值时异步函数还没有准备好。有人可以帮忙吗?谢谢!

你的功能看起来没问题,但作业需要更改为:

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);
    });
});

因为函数 returns 您等待的承诺,而该承诺的最终结果就是您的数据数组。