使用Promise等待轮询条件满足 [英] Use Promise to wait until polled condition is satisfied
问题描述
我需要创建一个JavaScript Promise,在特定条件为真之前无法解析。假设我有一个第三方库,我需要等到该库中存在某个数据条件。
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屋!