Use Promise to wait until polled condition is satisfied

后端 未结 5 608
孤独总比滥情好
孤独总比滥情好 2020-12-23 09:34

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 da

5条回答
  •  盖世英雄少女心
    2020-12-23 09:59

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

提交回复
热议问题