javascript - Kris Kowal 的设计 promise 文章

标签 javascript promise

我正在阅读 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/

相关文章:

javascript - 调用函数而不是重新加载页面

javascript - 日期选择器在另一个路由页面或在 vue js 中返回时不起作用?

javascript - 吞下消息 : Error: Uncaught (in promise): [object Undefined]

javascript - promise 链扩展

angularjs - 在 AngularJS 中,当使用 "controller as"语法和 "this"时,如何在 promise 的回调中引用 "this"?

javascript - Promise 控制流程 - catch 与 onRejected

javascript 正则表达式 - 测试不是函数

javascript - 同一按钮上的不同 Bootstrap 日期选择器

javascript - shopify-api-node 返回状态 401 未授权私有(private)应用程序

javascript - 在 div 中查找 div