Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

Are JavaScript forever-pending promises bad?

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

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);

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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...