[英]Parse Cloud Code Promise error handling
I'm kind of new to JS and really new to Promises. 我是JS的新手,也是Promises的新手。
Let's say I have a chain of 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.
});
I am refactoring a bunch of code that used callbacks and each error: function(error) {}
returned a custom error message. 我正在重构一堆使用回调和每个
error: function(error) {}
的代码error: function(error) {}
返回了一个自定义错误消息。 I want to be able to pass a custom error message depending on where the chain broke down. 我希望能够根据链损坏的位置传递自定义错误消息。
I figure it has something to do with fail() or reject() but I haven't figured out how. 我认为这与fail()或reject()有关,但我还没有弄清楚该怎么做。
I would like to know: 我想知道:
1: How can I return custom error messages like I want to? 1:如何返回想要的自定义错误消息?
2: Am I using promises correctly (based on what you see here?) 2:我是否正确使用了Promise(根据您在此处看到的内容?)
Thanks! 谢谢!
.fail
to add handlers as you suspected. .fail
添加怀疑的处理程序。 While your promises would function as written, they could be tidied up: 虽然您的诺言将像书面形式那样起作用,但可以将它们整理整齐:
isUserInCooldown
should include the hoursRemaining > 0
check so it doesn't pollute other functions. isUserInCooldown
应该包含hoursRemaining > 0
检查,这样它才不会污染其他功能。 challenge.save
doesn't depend on objectsToSave
, firing them both off simultaneously and using Parse.Promise.when
would be faster. challenge.save
不依赖于objectsToSave
,则同时触发它们并使用Parse.Promise.when
会更快。 response.success
or response.error
as cloud functions require. response.success
或response.error
。 What you did here is pointless, as I repeat to prove a point: 您在这里所做的事情毫无意义,我将再次证明这一点:
.then(function(challenge){
return Parse.Promise.as(challenge);
}).then(function(challenge){
return Parse.Promise.as(challenge);
}).then(function(challenge){
return Parse.Promise.as(challenge);
});
Ah, much better: 啊,好多了:
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)
Or, if you're not using cloud functions: 或者,如果您不使用云功能:
.fail(function(error) {
console.log(error); //logs "Couldn't save all" or "Couldn't save the challenge"
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.