如何应对悬空的承诺 [英] How to deal with dangling promises

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

问题描述

通常我想调用一个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", ... 事件,这些事件承诺

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天全站免登陆