Javascript:如何检查末尾没有 `fail` block 的 promise 链?

标签 javascript typescript jslint q flowtype

<分区>

我如何检查我的 Javascript 代码以识别末尾没有失败 block 的 promise 链 (promise.then().then().then()...)?是否有任何现有工具(JSHint、JSLint、Flow 静态类型检查器、Typescript ……?)允许这样做吗?

坦率地说,这样做的动机是有时我只是忘记在我编写的代码中放入一个。然后,如果该代码中出现错误,它将无提示地失败,并且调试起来非常困难。相反,更好的软件工程能够在 lint 时捕获这些错误,就像我可以使用 linting 识别变量名称中的拼写错误一样

例如:

q(this_function_returns_a_promise())
.then(function(data) {
  console.log('The promise returned some data: ' + JSON.stringify(data));
})
// .. more thens, spreads, alls
.then(function(modified_data) {
  this_function_will_throw_an_error(modified_data);
})
// .. more thens, spreads, alls
.then(function(modified_modified_data) {
  console.log('I will not be printed, logging and execution will just stop in ' +
    'the middle then()');
});
// if only there was a .fail(function(err) { ... }) here that printed the error!

最佳答案

这不是您可以检查或通过静态分析识别的东西。在许多(大多数?)情况下, promise 链不提供捕获并且不需要或不想提供捕获,因为捕获将发生在下游的某个地方。

您需要做的是使用您的 promise 库的工具来报告“僵尸”promises,或未捕获的被拒绝的 promises。这将发生在运行时,而不是“编译”时。如何做到这一点的细节因图书馆而异。一些浏览器已经开始沿着这条线实现。在 Chrome 中,尝试在控制台中输入以下内容:

> Promise.resolve().then(function() {throw "throw";})
< Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
< Uncaught (in promise) throw
  ^^^^^^^^^^^^^^^^^^^^^^^^^^^

关于Javascript:如何检查末尾没有 `fail` block 的 promise 链?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31068225/

相关文章:

json - JSLINT 错误消息与 JSON.parse()

javascript - JSLint 关于 Ajax 数据的警告

javascript - 解构 undefined object 数组

Javascript 平均计算器(用户输入的多个值)

javascript - React typescript 不可分配给类型参数

javascript - 在回调函数中引用更正这个

javascript - 是否有可用的 JSLint Eclipse 插件?

javascript - 如何使原型(prototype)中的对象不在 javascript 中共享

javascript - 标准 js 已弃用 '__proto__' 属性

typescript - 为什么 TypeScript 不识别 Vue 插件的模块扩充?