Use Promise to wait until polled condition is satisfied Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Use Promise to wait until polled condition is satisfied without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I need to create a JavaScript Promise that will not resolve until a specific condition is true. Let’s say I have a 3rd party library, and I need to wait until a certain data condition exists within that library.

The scenario I am interested in is one where there is no way to know when this condition is satisfied other than by simply polling.

I can create a promise that waits on it – and this code works, but is there a better or more concise approach to this problem?

function ensureFooIsSet() {
    return new Promise(function (resolve, reject) {
        waitForFoo(resolve);
    });
}

function waitForFoo(resolve) {
    if (!lib.foo) {
        setTimeout(waitForFoo.bind(this, resolve), 30);
    } else {
        resolve();
    }
}

Usage:

ensureFooIsSet().then(function(){
    ...
});

I would normally implement a max poll time, but didn’t want that to cloud the issue here.

Answer

A small variation would be to use a named IIFE so that your code is a little more concise and avoids polluting the external scope:

function ensureFooIsSet() {
    return new Promise(function (resolve, reject) {
        (function waitForFoo(){
            if (lib.foo) return resolve();
            setTimeout(waitForFoo, 30);
        })();
    });
}
We are here to answer your question about Use Promise to wait until polled condition is satisfied - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji