javascriptpromise

Use Promise to wait until polled condition is satisfied


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.


Solution

  • 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);
            })();
        });
    }