Lan*_*tig 5 javascript promise parse-platform react-native
当Parse for React Native中的一系列promise中抛出异常时,我注意到发生了一些非常奇怪的事情.承诺链永远不会解决,永远不会拒绝,并且永远不会抛出异常.它只是默默地消失.
这是重新创建问题的示例代码:
// Replacing this with Promise.resolve() prints the error.
// Removing this stage prints the error.
Parse.Promise.as()
// Removing this stage causes a red screen error.
.then(function() {
// Replacing this with Parse.Promise.as() causes a red screen error.
return Promise.resolve();
})
.then(function () {
throw new Error("There was a failure");
})
.then(function () { console.log("Success")}, function (err) { console.log(err) });
Run Code Online (Sandbox Code Playgroud)
正如您从评论中看到的那样,它似乎只发生在这个特定的事件序列中.删除一个阶段,或者交换一个原生JS承诺的Parse承诺会导致事情再次发生.(在我的实际代码中,"Promise.resolve()"阶段实际上是对返回promise的本机iOS方法的调用.)
我知道Parse承诺的行为与A +兼容的承诺完全不同(参见/sf/answers/2185625221/).实际上,Parse.Promise.enableAPlusCompliant()在此部分代码之前调用会导致异常被捕获并打印出来.但我认为Parse promises和原生JS承诺可以安全地一起使用.
为什么这个异常会默默地消失?
谢谢.
为什么这个异常消失了?
默认情况下,Parse 不会捕获异常,而 Promise 会吞掉异常。
Parse 不是 100% Promises/A+ 兼容,但它确实尝试同化从then回调返回的 thenables。它既不捕获异常也不异步执行自己的回调。
then您正在做的事情可以在不使用的情况下重现
var p1 = new Parse.Promise();
var p2 = new Parse.Promise();
// p2 should eventually settle and call these:
p2._resolvedCallbacks = [function (res) { console.log("Success") }];
p2._rejectedCallbacks = [function (err) { console.log(err) }];
function handler() {
throw new Error("There was a failure");
}
// this is what the second `then` call sets up (much simplified):
p1._resolvedCallbacks = [function(result) {
p2.resolve(handler(result)); // throws - oops
}];
// the native promise:
var p = Promise.resolve();
// what happens when a callback result is assimilated:
if (isThenable(p))
p.then(function(result) {
p1.resolve(result);
});
Run Code Online (Sandbox Code Playgroud)
问题是它p1.resolve是同步的,并且立即执行回调p1- 这反过来又会抛出异常。在可以调用之前通过抛出p2.resolve,p2将永远保持挂起状态。异常冒泡并完成p1.resolve()- 现在抛出对本机then方法的回调。本机 Promise 实现捕获异常并拒绝then由它返回的 Promise,但是在任何地方都会被忽略。
默默?
如果您的“本机”承诺实现支持未处理的拒绝警告,您应该能够看到被拒绝的承诺中存在的异常。
| 归档时间: |
|
| 查看次数: |
619 次 |
| 最近记录: |