javascript 使用“承诺”等待,直到满足轮询条件

umuewwlo  于 2023-03-06  发布在  Java
关注(0)|答案(6)|浏览(92)

我需要创建一个JavaScript Promise,它在特定条件为真之前不会解析。假设我有一个第三方库,我需要等到该库中存在特定的数据条件。
我感兴趣的场景是这样一种场景:除了简单的轮询之外,没有办法知道这个条件何时得到满足。
我可以创建一个等待它的承诺--这段代码是有效的,但是有没有更好或更简洁的方法来解决这个问题呢?

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

我通常会实现一个最大轮询时间,但不希望在这里混淆问题。

pbwdgjma

pbwdgjma1#

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

function ensureFooIsSet() {
    return new Promise(function (resolve, reject) {
        (function waitForFoo(){
            if (lib.foo) return resolve();
            setTimeout(waitForFoo, 30);
        })();
    });
}
yyhrrdl8

yyhrrdl82#

这是一个我经常使用的waitFor函数,你给它传递一个函数,它会检查并等待,直到函数返回一个真实值,或者直到它超时。

  • 这是一个简单的版本,说明了函数的作用,但您可能希望使用完整版本,在答案中进一步添加
let sleep = ms => new Promise(r => setTimeout(r, ms));
let waitFor = async function waitFor(f){
    while(!f()) await sleep(1000);
    return f();
};

示例用法:

  • 等待元素存在,然后将其赋给变量
let bed = await waitFor(() => document.getElementById('bedId'))
if(!bed) doSomeErrorHandling();
  • 等待变量为真
await waitFor(() => el.loaded)
  • 等待某个测试的结果
await waitFor(() => video.currentTime > 21)
  • 添加特定的超时以停止等待
await waitFor(() => video.currentTime > 21, 60*1000)
  • 传递给它一些其他的测试函数
if(await waitFor(someTest)) console.log('test passed')
else console.log("test didn't pass after 20 seconds")

完整版本:

这个版本比简单版本处理更多的情况,null、undefined、空数组等,有一个超时,一个频率可以作为参数传递,并将它对一些漂亮颜色的处理记录到控制台

function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms));}

/**
 * Waits for the test function to return a truthy value
 * example usage:
 *    wait for an element to exist, then save it to a variable
 *        let el = await waitFor(() => document.querySelector('#el_id')))
 *    timeout_ms and frequency are optional parameters
 */
async function waitFor(test, timeout_ms = 20 * 1000, frequency = 200) {
    if (typeof (test) != "function")     throw new Error("test should be a function in waitFor(test, [timeout_ms], [frequency])")
    if (typeof (timeout_ms) != "number") throw new Error("timeout argument should be a number in waitFor(test, [timeout_ms], [frequency])");
    if (typeof (frequency) != "number")  throw new Error("frequency argument should be a number in waitFor(test, [timeout_ms], [frequency])");
    let logPassed = () => console.log('Passed: ', test);
    let logTimedout = () => console.log('%c' + 'Timeout : ' + test, 'color:#cc2900');
    let last = Date.now();
    let logWaiting = () => { 
        if(Date.now() - last > 1000) {
            last = Date.now();
            console.log('%c' + 'waiting for: ' + test, 'color:#809fff'); 
        }
    }

    let endTime = Date.now() + timeout_ms;
    let isNotTruthy = (val) => val === undefined || val === false || val === null || val.length === 0; // for non arrays, length is undefined, so != 0    
    let result = test();
    while (isNotTruthy(result)) {
        if (Date.now() > endTime) {
            logTimedout();
            return false;
        }
        logWaiting();
        await sleep(frequency);
        result = test();
    }
    logPassed();
    return result;
}
quhf5bfb

quhf5bfb3#

有没有更简洁的方法来解决这个问题?
有了waitForFoo函数,构造函数中就不需要匿名函数了:

function ensureFooIsSet() {
    return new Promise(waitForFoo);
}

为了避免污染作用域,我建议要么将两者都 Package 在IIFE中,要么将waitForFoo函数移到ensureFooIsSet作用域中:

function ensureFooIsSet(timeout) {
    var start = Date.now();
    return new Promise(waitForFoo);
    function waitForFoo(resolve, reject) {
        if (window.lib && window.lib.foo)
            resolve(window.lib.foo);
        else if (timeout && (Date.now() - start) >= timeout)
            reject(new Error("timeout"));
        else
            setTimeout(waitForFoo.bind(this, resolve, reject), 30);
    }
}

或者,为了避免在resolvereject之间传递所需的绑定,您可以像@DenysSéguret建议的那样将其移动到Promise构造函数回调中。
有没有更好的办法?
就像@BenjaminGruenbaum评论的那样,你可以观察.foo属性的赋值,比如使用setter:

function waitFor(obj, prop, timeout, expected) {
    if (!obj) return Promise.reject(new TypeError("waitFor expects an object"));
    if (!expected) expected = Boolean;
    var value = obj[prop];
    if (expected(value)) return Promise.resolve(value);
    return new Promise(function(resolve, reject) {
         if (timeout)
             timeout = setTimeout(function() {
                 Object.defineProperty(obj, prop, {value: value, writable:true});
                 reject(new Error("waitFor timed out"));
             }, timeout);
         Object.defineProperty(obj, prop, {
             enumerable: true,
             configurable: true,
             get: function() { return value; },
             set: function(v) {
                 if (expected(v)) {
                     if (timeout) cancelTimeout(timeout);
                     Object.defineProperty(obj, prop, {value: v, writable:true});
                     resolve(v);
                 } else {
                     value = v;
                 }
             }
         });
    });
    // could be shortened a bit using "native" .finally and .timeout Promise methods
}

您可以像waitFor(lib, "foo", 5000)一样使用它。

t1rydlwq

t1rydlwq4#

下面是一个使用async/await和默认ES6 promise的实用函数,promiseFunction是一个异步函数(或者只是一个返回promise的函数),如果满足要求,它将返回一个真实值(如下所示)。

const promisePoll = (promiseFunction, { pollIntervalMs = 2000 } = {}) => {
  const startPoll = async resolve => {
    const startTime = new Date()
    const result = await promiseFunction()

    if (result) return resolve()

    const timeUntilNext = Math.max(pollIntervalMs - (new Date() - startTime), 0)
    setTimeout(() => startPoll(resolve), timeUntilNext)
  }

  return new Promise(startPoll)
}

示例用法:

// async function which returns truthy if done
const checkIfOrderDoneAsync = async (orderID) => {
  const order = await axios.get(`/order/${orderID}`)
  return order.isDone
}

// can also use a sync function if you return a resolved promise
const checkIfOrderDoneSync = order => {
  return Promise.resolve(order.isDone)
}

const doStuff = () => {
  await promisePoll(() => checkIfOrderDone(orderID))
  // will wait until the poll result is truthy before
  // continuing to execute code
  somethingElse()
}
hs1rzwqc

hs1rzwqc5#

function getReportURL(reportID) {
  return () => viewReportsStatus(reportID)
  .then(res => JSON.parse(res.body).d.url);
}

function pollForUrl(pollFnThatReturnsAPromise, target) {
  if (target) return P.resolve(target);
  return pollFnThatReturnsAPromise().then(someOrNone => pollForUrl(pollFnThatReturnsAPromise, someOrNone));
}

pollForUrl(getReportURL(id), null);
13z8s7eq

13z8s7eq6#

很简单!等到一个变量有了X值。在这个例子中,我们等到zzz = 99。

var zzz=0;
const promise2 = new Promise((resolve, reject) => {
    const loop = () =>{
        zzz == 99   ? resolve(zzz) : setTimeout(loop);
    } 
    loop();
});
promise2.then((value) => {
    alert( "oki:"+value );
});

相关问题