如何处理悬而未决的承诺 [英] How to deal with dangling promises

查看:25
本文介绍了如何处理悬而未决的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常想调用一个promise,让它异步运行而不是等待它.喜欢:

Oftentimes I want to call a promise and just let it run asynchronously instead of waiting for it. Like:

... some code ...

fetchMyCount().then(count => {
  updateTheUI(count);
});

... more code ...

现在这很好用,但通常我不会在承诺上放置失败处理程序,因为这对每个人来说都非常繁重.这就像在我的每个数据提取上放置一个 try {} catch {}.

Now this works great, but oftentimes I don't put a failure handler on the promise because that is pretty onerous for each one. That would be like putting a try {} catch {} on every one of my data fetches.

问题是,如果它失败了,它会默默地这样做.它不会抛出我的 window.onerror 可以获得的异常,它不会记录,也不会执行任何操作.

The problem is, if it fails, it does so silently. It doesn't throw an exception that my window.onerror can get, it doesn't log, it doesn't do anything.

现在我可以制作一个漂亮的包装器,例如:

Now I can make a nice wrapper like:

Async(fetchMycount().then(count => {
  updateTheUI(count);
}));

通常可以处理 Promise,但是我必须记住包装每个异步调用.

which can generically deal with promises, but then I have to remember to wrap each and every async call.

有没有办法拥有像 window.onerror 这样的顶级处理程序或一个大的 try {} catch {} 包装器,可以捕获所有未处理的 -有被拒绝的承诺,所以我可以记录它们并确保它们得到修复?

Is there a way to have a top-level handler like window.onerror or a big try {} catch {} wrapper that can catch all un-dealt-with rejected promises so I can log them and make sure they get fixed?

推荐答案

这是一个常见的用例.你的问题是真实的.在 Node 中,你有 process.on("unhandledRejection", ... 事件 你可以使用.遗憾的是,这些在浏览器中尚不可用.一些与 ES2015 兼容的库 承诺 offer它们,你可以使用它们,直到原生 promise 得到支持.

This is a common use case. Your problem is real. In Node, you have process.on("unhandledRejection", ... events which you can use. Sadly, these are not available in browsers yet. Some libraries which are compatible with ES2015 promises offer them and you can use those until native promises get support.

好处是即将在浏览器中提供支持,并且浏览器最终会支持这些钩子.

The upside is that support in browsers is coming and browsers will eventually support these hooks.

目前,我已经说服 polyfill 添加它,所以如果您使用的是 core-js polyfill,您可以这样做:

Currently, I've convinced the polyfill to add it, so if you're using the core-js polyfill you can do:

window.onunhandledrejection = function(e){
    // handle here e.promise e.reason
};

请注意,这假设在以下情况下某些内容是未处理的拒绝:未处理,并且错误处理程序未同步附加(准确地说是在任务中).

Note that this assumes that something is an unhandled rejection if: It's unhandled, and an error handler was not attached synchronously (within a task to be precise).

这篇关于如何处理悬而未决的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆