使用Promise等待轮询条件满足

时间:2015-05-28 11:57:44

标签: javascript promise

我需要创建一个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(){
    ...
});

我通常会实施最长轮询时间,但不希望这样在此处解决问题。

5 个答案:

答案 0 :(得分:50)

一个小的变化是使用命名的IIFE,以便您的代码更简洁,并避免污染外部范围:

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

答案 1 :(得分:5)

  

这个问题有更简洁的方法吗?

好吧,使用waitForFoo函数,您根本不需要构造函数中的匿名函数:

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

为了避免污染范围,我建议将两者都包装在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所需的绑定,您可以将其移动到@ {DenisSéguret建议的Promise构造函数回调中。

  

有更好的方法吗?

与@BenjaminGruenbaum评论一样,您可以观看要分配的.foo媒体资源,例如使用二传手:

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)一样使用它。

答案 2 :(得分:2)

这是一个使用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()
}

答案 3 :(得分:0)

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

答案 4 :(得分:0)

这是我经常使用的waitFor函数。您向它传递一个函数,然后运行它,直到该函数返回真实值或超时为止。 用法示例:

// wait for an element to exist, then assign it to a variable 
let bed = await waitFor(()=>document.getElementById('_1vd7r9f'))
if(!bed) doSomeErrorHandling();
// wait for a variable to be truthy
await waitFor(()=>el.loaded)
// wait for some test to be true
await waitFor(()=>video.currentTime>21)
// add a specific timeout
await waitFor(()=>video.currentTime>21, 60*1000)
// send an element as an argument once it exists
doSomething(await waitFor(()=>selector('...'))
// pass it some other test function
if(await waitFor(someTest)) console.log('test passed')
else console.log("test didn't pass after 20 seconds")

这是它的代码

function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms));    }
/* Waits for test function to return a truthy value
example usage:
    // wait for an element to exist, then save it to a variable
    var el = await waitFor(()=>$('#el_id')))                 // second timeout argument optional, or defaults to 20 seconds
 */
async function waitFor(test, timeout_ms=20*1000){
    return new Promise(async(resolve,reject)=>{
        if( typeof(timeout_ms) != "number") reject("Timeout argument not a number in waitFor(selector, timeout_ms)");
        var freq = 100;
        var result
        // wait until the result is truthy, or timeout
        while( result === undefined || result === false || result === null || result.length === 0 ){  // for non arrays, length is undefined, so != 0
            if( timeout_ms % 1000 <freq)        console.log('%c'+'waiting for: '+ test,'color:#809fff' );
            if( (timeout_ms -= freq) < 0 ){     console.log('%c'+'Timeout : '   + test,'color:#cc2900' );
                resolve(false);
                return;
            }
            await sleep(freq);
            result = typeof(test) === 'string' ? eval(test) : test();       // run the test and update result variable
        }
        // return result if test passed
        console.log('Passed: ', test);
        resolve(result);
    });
}