Javascript:我如何检查末尾没有“失败”块的承诺链?

Javascript: How can I lint for promise chains that do not have a `fail` block at the end?

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

坦率地说,这样做的动机是有时我只是忘记在我编写的代码中放入一个。然后,如果该代码中出现错误,它将无提示地失败,并且调试起来非常困难。相反,更好的软件工程能够在 lint-time 中捕获这些错误,就像我可以使用 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 库的工具来报告 "zombie" promises 或未捕获的被拒绝的 promises。这将发生在 运行 时间,而不是 "compile" 时间。如何做到这一点的细节因图书馆而异。一些浏览器已经开始沿着这条线实现。在 Chrome 中,尝试在控制台中输入以下内容:

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