使用 Promise 等待轮询条件满足 [英] Use Promise to wait until polled condition is satisfied

查看:50
本文介绍了使用 Promise 等待轮询条件满足的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个在特定条件为真之前不会解析的 JavaScript Promise.假设我有一个 3rd 方库,我需要等到该库中存在某种数据条件.

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

用法:

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

我通常会实施最大轮询时间,但不希望这会掩盖这里的问题.

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

推荐答案

一个小的变化是使用命名的 IIFE,这样你的代码会更简洁一点,避免污染外部作用域:

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

这篇关于使用 Promise 等待轮询条件满足的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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