A simple polling utility that executes a function for a specified time period until a truthy value is returned or the specified duration has passed.
Installation
npm install try-for
Usage
Promise
const tryFor = require('try-for');
let result;
setTimeout(() => {
result = 'Fin';
}, 2000);
const checkResult = () => result;
tryFor(checkResult, 5000)
.then(result => {
if (result) {
console.log(result);
} else {
console.log('No result')
}
});
Async/await
const tryFor = require('try-for');
let result;
setTimeout(() => {
result = 'Fin';
}, 2000);
const checkResult = () => result;
(async function test() {
const result = await tryFor(checkResult, 5000);
if (result) {
console.log(result);
} else {
console.log('No result');
}
})();
API
tryFor(func, duration, [optional: ms])
func
- A function that will be called each poll iteration. Return any truthy value to exit early and a non-truthy value to continue polling.
duration
- How long (in milliseconds) the poll should stay active before giving up.
ms
- Interval (in milliseconds) between polls. Default is every 100ms.
Examples
In these examples, we use local storage for our test. We begin with an empty local storage object, set a timer to create a new item 2 seconds after our code is executed, and immediately begin listening for our new item every 100ms for the next 5 seconds.
Promise
const tryFor = require('try-for');
// Remove existing local storage item(s)
localStorage.clear();
// In 2 seconds, create our 'test' local storage item
setTimeout(() => localStorage.setItem('test', '1234'), 2000);
// Begin polling local storage for item 'test'
// and continue for 5 seconds
tryFor(() => localStorage.getItem('test'), 5000)
.then(result => {
if (result) {
console.log('Result found: ', result); // Result found: 1234
} else {
console.log('Result not found in specified time');
}
});
Async/await
const tryFor = require('try-for');
(async function test() {
localStorage.clear();
setTimeout(() => localStorage.setItem('test', '1234'), 2000);
const result = await tryFor(() => localStorage.getItem('test'), 5000);
if (result) {
console.log('Result found: ', result); // Result found: 1234
} else {
console.log('Result not found in specified time');
}
})();
ms
option
With const tryFor = require('try-for');
localStorage.clear();
setTimeout(() => localStorage.setItem('test', '1234'), 2000);
// Poll every 5ms
tryFor(() => localStorage.getItem('test'), 5000, 5)
.then(result => {
if (result) {
console.log('Result found: ', result); // Result found: 1234
} else {
console.log('Result not found in specified time');
}
});