2016-01-28 26 views
4

我被这个问题困住了,找不到答案。我在Cloud Code中编写了以下函数。Parse.com/CloudCode Promises不太清楚

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

因此,它似乎是异步函数IST没有准备好时,在作出转让。任何人都可以帮忙吗?谢谢!

回答

3

你的函数看起来不错,但工作需要更改为:

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

,因为该函数返回您等待和承诺的最终结果是你的数据阵列的承诺。

+0

啊!现在我懂了。 “then”函数将返回的promise作为参数。非常感谢! – weka1