pha*_*zei 6 node.js promise parse-platform
我有一个承诺可能会失败的情况,但我希望能够处理它,并继续下一个.我试图从失败的catch中返回一个成功的promise,但是它给出了一个没有方法设置的返回对象的错误.这可能吗?我该怎么办呢?
Parse.Promise.as(1).then(function() {
if (user.get('vendor')) {
//fetch returns a promise
return user.get('vendor').fetch();
}
return new Vendor();
}).fail(function() {
//this will be called if the fetch fails, in that case, just return new Vendor();
return Parse.Promise.as(function() {
//this will be a valid promise so should hopefully return to the next then, but it doesn't work
return new Vendor();
});
}).then(function(result) {
vendor = result;
//continue with stuff
}).fail(function(error) {
res.json(400, {
"result": false,
"error": error
});
});
Run Code Online (Sandbox Code Playgroud)
编辑:
我尝试将其更改为:
Parse.Promise.as(1).then(function() {
if (user.get('vendor')) {
return user.get('vendor').fetch();
}
return new Vendor();
}).then(null, function() {
//if the fetch fails, this will return a successful Promise with Vendor object
console.log("failed fetch");
return new Vendor();
}).then(function(result) {
console.log("vendor retrieved");
}).then(null, function(error) {
console.log('error');
});
Run Code Online (Sandbox Code Playgroud)
但是记录:fetch错误失败
这是Parse的做法,还是其他错误?
EDIT2:
如果我改变了,似乎工作
return new Vendor();
Run Code Online (Sandbox Code Playgroud)
到
return Parse.Promise.as(1).then(function() { return new Vendor(); });
Run Code Online (Sandbox Code Playgroud)
(编辑)或这个:
return Parse.Promise.as(new Vendor());
Run Code Online (Sandbox Code Playgroud)
就像你说的那样,可以通过承诺从异常中恢复:
try{
mightThrow()
} catch (e){
// handle
}
thisWillRunRegardless();
Run Code Online (Sandbox Code Playgroud)
或者使用Parse承诺:
Promise.as(1).then(function(){
mightThrow();
}).then(null,function(e){
// handle
}).then(function(){
thisWillRunRegardless();
});
Run Code Online (Sandbox Code Playgroud)
使用其他promise库可能看起来像:
Promise.try(function(){
mightThrow();
}).catch(function(){
//handle
]).then(thisWillRunRegardless);
Run Code Online (Sandbox Code Playgroud)
上面代码的问题是.fail.由于parse.com承诺是jQuery投诉 - 他们的失败方法就像jQuery一样.它添加了一个失败处理程序并返回相同的promise.
不知道他们为什么这样做,但是哦.你需要改变.fail(function(){,以.then(null,function(){...代替.第二个参数 .then得到的是拒绝处理程序.