我正在阅读 Kris Kowal 的 design article关于 promise 。
我有一个关于 blah 函数的问题。
为什么这个函数在某些情况下会抛出异常?
如何重现这种异常(exception)情况?
Safety and Invariants
var blah = function () {
var result = foob().then(function () {
return barf();
});
var barf = function () {
return 10;
};
return result; };
This function will either throw an exception or return a promise that will quickly be fulfilled with the value of 10. It depends on whether foob() resolves in the same turn of the event loop (issuing its callback on the same stack immediately) or in a future turn. If the callback is delayed to a future turn, it will allways succeed.
最佳答案
这只是 JavaScript,因为 barf
是在 then
回调被注册之后定义的 - 如果同步调用 then 回调 - 它会还没有定义,它会和做的一样:
(undefined)();
这是一个错误。说明:
// this code works
setTimeout(function(){
foo("HI");
});
var foo = alert;
// this code throws
(function(){
foo("Hi");
})();
var foo = alert;
Promise 库确保在引擎执行平台代码时始终调用回调 - 因此对于 Promises,如果它们符合 Promises/A(+) 标准,这就不是问题。例如,jQuery 的 promise 在这里会失败,这取决于 foob
是否在 jQuery 1 和 2 而不是 3(他们修复了它)中得到解决。
关于javascript - Kris Kowal 的设计 promise 文章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33699046/