2016-01-28 25 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