2015-10-13 33 views
0

我對JS很陌生,對Promises真的很陌生。解析雲代碼承諾錯誤處理

比方說,我有諾言鏈:

//var challenge is created before all this 

isUserInCooldown().then(function(hoursRemaining) 
{ 
    if (hoursRemaining > 0) 
    { 
     return Parse.Promise.error("You can't challenge 'cuz you're on cooldown."); 
    } 

    var objectsToSave = []; 

    //DO SOME STUFF TO THE OBJECTS 

    return Parse.Object.saveAll(objectsToSave); 

}).then(function(list) 
{ 
    //DO SOME STUFF TO CHALLENGE 

    return challenge.save(null); 

}).then(function(challenge) 
{ 
    return Parse.Promise.as(challenge); 
}, 
function(error) 
{ 
    if (theSaveAllFailed) { return "Couldn't save all"; } 
    if (theSaveFailed) { return "Couldn't save the challenge"; } 
    //etc. 
}); 

我重構了一堆所使用的回調代碼和每個error: function(error) {}返回自定義錯誤消息。我希望能夠傳遞一個自定義錯誤消息,這取決於鏈斷裂的位置。

我認爲它與fail() or reject()有關,但我還沒有想出如何。

我想知道:

1:我怎樣才能返回自定義錯誤消息像我想?

2:(?根據你在這裏看到的)上午正確使用承諾我

謝謝!

回答

0
  1. 如果你想覆蓋一個承諾拒絕的錯誤信息,您可以使用.fail你懷疑添加處理程序。
  2. 雖然書面你的承諾將發揮作用,他們可以收拾:

    • isUserInCooldown應包括hoursRemaining > 0檢查,因此不會污染等功能。
    • 如果challenge.save不依賴objectsToSave,同時關閉它們並使用Parse.Promise.when會更快。
    • 因爲雲功能需要,您絕不會撥打response.successresponse.error

你在這裏做什麼是沒有意義的,因爲我再說一遍,以證明這一點:

.then(function(challenge){ 
    return Parse.Promise.as(challenge); 
}).then(function(challenge){ 
    return Parse.Promise.as(challenge); 
}).then(function(challenge){ 
    return Parse.Promise.as(challenge); 
}); 

嗯,好多了:

isUserInCooldown().then(function() { 
    return Parse.Object.saveAll(objectsToSave).fail(function(){ 
    return "Couldn't save all"; 
    }); 
}).then(function(){ 
    return challenge.save().fail(function(){ 
    return "Couldn't save the challenge"; 
    }); 
}).then(response.success, response.error) 

或者,如果你不使用雲端功能:

.fail(function(error) { 
    console.log(error); //logs "Couldn't save all" or "Couldn't save the challenge" 
});