JavaScript 永远未决的承诺是坏的吗? [英] Are JavaScript forever-pending promises bad?

查看:10
本文介绍了JavaScript 永远未决的承诺是坏的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为 myProm 的 promise,并假设我有一个名为 onSuccessonError 的成功和错误处理程序.

Say I have a promise called myProm, and say I have success and error handlers called onSuccess and onError.

每当我的承诺需要超过 10 秒才能完成时,我希望执行一个名为 timeoutHandler 的函数,但如果发生这种情况,onSuccessonError 应该被执行.(同样,如果 onSuccessonError 运行,我不希望我的 timeoutHandler 被执行.)

Whenever my promise takes longer than 10 seconds to complete, I want a function called timeoutHandler to be executed, but if that happens, neither onSuccess nor onError should be executed. (Similarly, if either onSuccess or onError runs, I don't want my timeoutHandler to be executed.)

我为此想出了以下代码片段.

I've come up with the following snippet for this.

new Promise((suc, err) => {
    let outOfTime = false;
    const timeoutId = window.setTimeout(() => {
        outOfTime = true;
        timeoutHandler();
    }, 10000);
    myProm.then(
        (...args) => {
            if (!outOfTime) {
                window.clearTimeout(timeoutId);
                suc(...args);
            }
        },
        (...args) => {
            if (!outOfTime) {
                window.clearTimeout(timeoutId);
                err(...args);
            }
        }
    );
}).then(onSuccess, onError);

但是,在超时的情况下,我新定义的承诺将永远挂起.这会产生任何负面影响吗?例如,运行时无法清理 Promise 对象,因为它仍然处于挂起状态(或类似的事情).

However, in case of a timeout, my newly defined promise will be forever-pending. Could this have any negative side effects? For example, the runtime not being able to clean up the Promise object because it's still pending (or something along those lines).

推荐答案

应该没有副作用.如果处于任何状态的非引用 Promise 保留资源,这将是浏览器错误.

There should be no side effect. It would be a browser bug if a non-referenced Promise in whatever state is keeping resources.

只要确保你没有保留对 Promise 对象的任何引用,你就会没事的.

Just make sure you don't keep any reference to the Promise object and you'll be fine.

请注意,某些 API(例如 setTimeout)会保留对闭包的引用直至超时值.这意味着如果你有一个很长的超时时间,比如 10 秒,你应该在不再需要它时立即清除它.否则,您的代码可以在 10 秒内调用数千个 setTimeout,并且每个都将保留对闭包的引用,在您的情况下,它将引用 Promise.

Beware that certain APIs such as setTimeout will keep a reference to the closure up to the timeout value. This means that if you have a long timeout, like the 10s one, you should clear it as soon as you don't need it anymore. Otherwise your code can call thousands of setTimeout within 10s, and each of them will keep a reference to the closure, which in your case will reference the Promise.

这篇关于JavaScript 永远未决的承诺是坏的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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