I want to keep calling asnchronous api requests repeatedly until it exceeds specified time. Using async-retry we can only specify retrycount and interval, we wanted to specify even timeout in the parameter.
Can you just suggest a way?
// try calling apiMethod 3 times, waiting 200 ms between each retry
async.retry({times: 3, interval: 200}, apiMethod, function(err, result) {
// do something with the result
});
Here is what you want :
const scheduleTrigger = (futureDate) => {
const timeMS = new Date(futureDate) - new Date();
return new Promise((res, ref) => {
if (timeMS > 0) {
setTimeout(() => {
res();
}, timeMS);
} else {
rej();
}
})
}
//const futureDate = '2020-07-23T20:53:12';
// or
const futureDate = new Date();
futureDate.setSeconds(futureDate.getSeconds() + 5);
console.log('now');
scheduleTrigger(futureDate).then(_ => {
console.log('future date reached');
// start whatever you want
stopFlag = false;
}).catch(_ => {
// the date provided was in the past
});
const wait = (ms = 2000) => {
return new Promise(res => {
setTimeout(_ => {
res();
}, ms);
})
}
const asyncFn = _ => Promise.resolve('foo').then(x => console.log(x));
let stopFlag = true;
(async () => {
while (stopFlag) {
await asyncFn();
await wait();
}
})();
So you want to keep retrying for as long as its within a certain timeout? How about this:
// Allow retry until the timer runs out
let retry = true;
const timeout = setTimeout(() => {
// Set retry to false to disabled retrying
retry = false;
// Can also build in a cancel here
}, 10000); // 10 second timeout
const retryingCall = () => {
apiMethod()
.then(response => {
// Optionally clear the timeout
clearTimeout(timeout);
})
.catch(() => {
// If retry is still true, retry this function again
if (retry) {
retryingCall();
}
});
};
You can achieve what you want with this function:
const retryWithTimeout = ({ timeout, ...retryOptions}, apiMethod, callback) => {
let timedout = false;
const handle = setTimeout(
() => (timedout = true, callback(new Error('timeout'))),
timeout
);
return async.retry(
retryOptions,
innerCallback => timedout || apiMethod(innerCallback),
(err, result) => timedout || (clearTimeout(handle), callback(err, result))
)
};
It has the advantage of allowing you to use the functionality of async.retry, as you apparently want, and also allows the timeout to take place even when what exceeds the timeout is the apiMethod itself, not the waiting time.
Usage example:
retryWithTimeout(
{timeout: 305, times: 4, interval: 100},
(callback) => { callback('some api error'); },
(err, result) => console.log('result', err, result)
)
Related
I have this:
this.toggleWaiting()
this.results = await this.query(term)
this.toggleWaiting()
First a loading spinner gets triggered.
Then the query runs.
And when the query function ended the loading spinner gets closed.
But what if I want to just show the loading spinner, when the query takes maybe more then 0.5 seconds?
Is there a simple way to do this?
A way to achieve this is to pass the this.query(term) promise to a function which will handle triggering the toggleWaiting only when the query takes longer than the specified amount of time (using the timeout).
For example, the below takes a promise, a function (waitingFn) which will be called with the isWaiting status as well as a timeout which you can use to specify how long you want to wait before you show the loading spinner. Finally, when the promise has been fulfilled, we return the result:
async function handleWaiting(promise, waitingFn, timeout) {
let loadingStarted = false;
let timeoutInstance = null;
const timeoutPromise = new Promise((res) => {
timeoutInstance = setTimeout(() => {
loadingStarted = true;
waitingFn(true);
}, timeout);
return res();
});
function onFinished() {
clearTimeout(timeoutInstance);
if (loadingStarted) {
waitingFn(false);
}
}
try {
const [result] = await Promise.all([promise, timeoutPromise]);
onFinished();
return result;
} catch (ex) {
onFinished();
throw ex;
}
}
You can call the handleWaiting function like so:
const result = await handleWaiting(this.query(term), (isWaiting) => this.toggleWaiting(), 500);
As #FZs and #Bergi have pointed out (thank you both), the below is an antipattern due to using the promise constructor:
function handleWaiting(promise, waitingFn, timeout) {
return new Promise((res, rej) => {
let loadingStarted = false;
const timeoutInstance = setTimeout(() => {
loadingStarted = true;
waitingFn(true);
}, timeout);
function onFinished() {
if (loadingStarted) {
waitingFn(false);
}
clearTimeout(timeoutInstance);
}
return promise
.then((result) => {
onFinished();
res(result);
})
.catch((ex) => {
onFinished();
rej(ex);
});
});
}
Thanks to ljbc1994 I found a nice solution.
Inside my alpineJs object - I have this implementation:
{
waiting: false,
async handleWaiting(promise, timeout) {
return new Promise((res, rej) => {
let loadingStarted = false;
const timeoutInstance = setTimeout(() => {
loadingStarted = true;
this.waiting = true;
}, timeout);
const onFinished = () => {
if (loadingStarted) {
this.waiting = false;
}
clearTimeout(timeoutInstance);
}
promise
.then((result) => {
onFinished();
res(result);
})
.catch((ex) => {
onFinished();
rej(ex);
});
});
},
async searchForTerm(term) {
this.results = await this.handleWaiting(this.$wire.query(term), 500);
// do something with the results...
},
}
Pretty straightforward.
For someone who is interested in the full code - here is the commit inside the github repo:
https://github.com/MichaelBrauner/sunfire-form/commit/7c1f8270e107a97b03264f5ddc5c3c3ae6f7cfd7
I want to test the following code:
const poll = (maxTries, interval, channel, stopTime) => {
let reached = 1;
const someInformation = someGetter();
const fetchData = async (resolve, reject) => {
const data = await networkClass.someApiCall();
if (data.stopTime === 1581516005) {
console.log("cond true");
someInformation.meta1 = transFormer(someInformation);
someInformation.meta2 = transFormer(someInformation);
someInformation.meta3 = {
...someInformation.meta1,
data,
};
resolve(someInformation);
} else if (reached < maxTries) {
reached += 1;
console.log("do it again");
setTimeout(fetchData, interval, resolve, reject);
} else {
reject(new Error('max retries reached'));
}
};
return new Promise(fetchData);
};
const checkForUpdates = () => {
setTimeout(() => {
poll(/* max retries */ 10, /* polling interval */ 1000, channel, stopTime)
.then((res) => {
setData(res);
console.log({ res: res.meta3.data });
})
.catch((e) => console.log({ e }));
}, 20000);
};
The test looks like that:
it(`should do stuff`, () => {
jest.spyOn(networkClass, 'someApiCall')
.mockResolvedValueOnce({ stopTime })
.mockResolvedValueOnce({ stopTime })
.mockResolvedValueOnce({ stopTime: 1581516005 });
checkForUpdates();
jest.advanceTimersByTime(40000);
expect(setDataMock).toHaveBeenCalled();
});
That console.log (console.log("do it again");) is only printed once, as if the test would not be able to call a setTimeout within a setTimeout. Do you have any ideas what might help?
Hello I'm new to javascript and wondering if there is a way to covnert below setInterval thingy into a promise so that .then could be used instead of the callback. Any help?
My ideas:
With a setTimeout I could resolve after a fixed time. But I'm not getting any ideas dealing with setInterval...
function alert_above(scrip, price, callback) {
var intvl = setInterval(() => {
if (get_last_price(scrip) > price) {
callback();
clearInterval(intvl);
}
}, 1000);
return intvl;
}
You can create a promise function that resolves asynchronously. Read more about Promise Here
function myInterval() {
return new Promise(resolve => {
const intId = setInterval(() => {
clearInterval(intId);
resolve();
}, 1000)
})
}
myInterval().then(() => {
console.log('Called after 1 second');
})
I think you could wrap into a new Promise like :
function promisifySetInterval(time) {
var defer = new Promise(resolve => {
let counter = 0
var intvl = setInterval(() => {
if (counter > time) {
resolve('hey');
clearInterval(intvl);
} else {
counter += 1000
}
}, 1000);
})
return defer;
}
promisifySetInterval(2000).then(param => {
console.log('hey', param)
})
And for youre case something like this :
function alert_above(scrip, price) {
var defer = new Promise(resolve => {
var intvl = setInterval(() => {
if (get_last_price(scrip) > price) {
resolve('hey');
clearInterval(intvl);
}
}, 1000);
})
return defer;
}
alert_above().then(param => {
console.log('hey', param)
})
Note: poll will be executed without delay the first time, which is different from the native setInterval.
Q: Why is poll based on setTimeout not setInterval?
A: Please see Execute the setInterval function without delay the first time.
Implementation:
// Promisify setTimeout
const pause = (ms, cb, ...args) =>
new Promise((resolve, reject) => {
setTimeout(async () => {
try {
resolve(await cb?.(...args))
} catch (error) {
reject(error)
}
}, ms)
})
// Promisify setInterval
const poll = async (interval, times, cb, ...args) => {
let result
const resolve = value => (times = 0) || (result = value)
const reject = reason => (times = 0) || (result = Promise.reject(reason))
await (async function basePoll() {
if (times > 0) {
const _result = await cb(...args, resolve, reject)
if (times) {
result = _result
--times && (await pause(interval, basePoll))
}
}
})()
return result
}
Tests:
import ordinal from 'ordinal'
// Test 1
poll(1000, 3, (a, b, c) => [a, b, c], 1, 2, 3).then(value => console.log(value))
// Test 2
let times = 0
poll(1000, 5, resolve => {
console.log(`${ordinal(++times)} time`)
times === 3 && resolve('resolved')
}).then(value => console.log(value))
// Test 3
let times = 0
poll(1000, 5, (resolve, reject) => {
console.log(`${ordinal(++times)} time`)
times === 3 && reject('rejected')
}).catch(error => console.error(error))
This question already has answers here:
How to cancel timeout inside of Javascript Promise?
(4 answers)
Closed 3 months ago.
This function is used to wait for millis number of second.
function delay(millis: number) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, millis);
});
My goal is then to return the timeout out of this function?
const timeout = await delay(20000);
on click somewhere else, user bored of waiting
clearTimeout(timeout)
Simply extend the Promise object you'll be sending:
function delay( millis ) {
let timeout_id;
let rejector;
const prom = new Promise((resolve, reject) => {
rejector = reject;
timeout_id = setTimeout(() => {
resolve();
}, millis);
});
prom.abort = () => {
clearTimeout( timeout_id );
rejector( 'aborted' );
};
return prom;
}
const will_abort = delay( 2000 );
const will_not_abort = delay( 2000 );
will_abort
.then( () => console.log( 'will_abort ended' ) )
.catch( console.error );
will_not_abort
.then( () => console.log( 'will_not_abort ended' ) )
.catch( console.error );
setTimeout( () => will_abort.abort(), 1000 );
You can return the resolve / reject along with the promise
function delay(millis) {
let reolver;
return [new Promise((resolve, reject) => {
resolver = resolve
x = setTimeout(() => {
resolve();
}, millis);
}), resolver];
}
const [sleep1, wake1] = delay(2000)
sleep1.then((x) => console.log(x || 'wakeup 1')) // Auto wake after 2 seconds
const [sleep2, wake2] = delay(2000)
sleep2.then((x) => console.log(x || 'wakeup 2'))
wake2('Custom Wakeup') // sleep2 cancelled will wake from wake2 call
You can use an AbortSignal:
function delay(ms, signal) {
return new Promise((resolve, reject) => {
function done() {
resolve();
signal?.removeEventListener("abort", stop);
}
function stop() {
reject(this.reason);
clearTimeout(handle);
}
signal?.throwIfAborted();
const handle = setTimeout(done, ms);
signal?.addEventListener("abort", stop);
});
}
Example:
const controller = new AbortController()
delay(9000, controller.signal).then(() => {
console.log('Finished sleeping');
}, err => {
if (!controller.signal.aborted) throw err;
// alternatively:
if (err.name != "AbortError") throw err;
console.log('Cancelled sleep before it went over 9000')
});
button.onclick => () => {
controller.abort();
};
You can return a function which cancels the timer (cancelTimer) along with the Promise object as an array from the delay function call.
Then use the cancelTimer to clear it if required and which would also reject the Promise:
function delay(millis) {
let cancelTimer;
const promise = new Promise((resolve, reject) => {
const timeoutID = setTimeout(() => {
resolve("done");
}, millis);
cancelTimer = () => {
clearTimeout(timeoutID);
reject("Promise cancelled");
};
});
return [promise, cancelTimer];
}
//DEMO
let [promiseCancelled, cancelTimer] = delay(20000);
(async() => {
try {
console.log("Promise result never printed", await promiseCancelled);
} catch (error) {
console.error("Promise is rejected", error);
}
})();
cancelTimer();
const [promise, _] = delay(2000);
(async() => {
console.log("Promise result printed", await promise);
})();
I recommend that you do not modify the promise by attaching an .abort method to it. Instead return two values from your delay function
the delayed value
a function that can be called to cancel the timeout
Critically, we do not see "x" logged to the console because it was canceled -
function useDelay (x = null, ms = 1000)
{ let t
return [
new Promise(r => t = setTimeout(r, ms, x)), // 1
_ => clearTimeout(t) // 2
]
}
const [x, abortX] =
useDelay("x", 5000)
const [y, abortY] =
useDelay("y canceled x", 2000)
x.then(console.log, console.error)
y.then(console.log, console.error).finally(_ => abortX())
console.log("loading...")
// loading...
// y canceled x
interactive demo
Here's an interactive example that allows you to wait for a delayed value or abort it -
function useDelay (x = null, ms = 1000)
{ let t
return [
new Promise(r => t = setTimeout(r, ms, x)), // 1
_ => clearTimeout(t) // 2
]
}
const [ input, output ] =
document.querySelectorAll("input")
const [go, abort] =
document.querySelectorAll("button")
let loading = false
function reset ()
{ loading = false
input.value = ""
go.disabled = false
abort.disabled = true
}
function load ()
{ loading = true
go.disabled = true
abort.disabled = false
}
go.onclick = e => {
if (loading) return
load()
const [delayedValue, abortValue] =
useDelay(input.value, 3000)
abort.onclick = _ => {
abortValue()
reset()
}
delayedValue
.then(v => output.value = v)
.catch(e => output.value = e.message)
.finally(_ => reset())
}
code { color: dodgerblue; }
<input placeholder="enter a value..." />
<button>GO</button>
<button disabled>ABORT</button>
<input disabled placeholder="waiting for output..." />
<p>Click <code>GO</code> and the value will be transferred to the output in 5 seconds.</p>
<p>If you click <code>ABORT</code> the transfer will be canceled.</p>
Just use an AbortSignal:
/**
* Sleep for the specified number of milliseconds, or until the abort
* signal gets triggered.
*
* #param ms {number}
* #param signal {AbortSignal|undefined}
*/
const sleep = (ms, signal) =>
new Promise<void>((ok, ng) => {
/** #type {number} */
let timeout
const abortHandler = () => {
clearTimeout(timeout)
const aborted = new Error(`sleep aborted`)
aborted.name = 'AbortError'
ng(aborted)
}
signal?.addEventListener('abort', abortHandler)
timeout = setTimeout(() => {
signal?.removeEventListener('abort', abortHandler)
ok()
}, ms)
})
> const a = new AbortController()
undefined
> const s = sleep(900000, a.signal)
undefined
> a.abort()
undefined
> await s
Uncaught AbortError: sleep aborted
at AbortSignal.abortHandler
at innerInvokeEventListeners
at invokeEventListeners
at dispatch
at AbortSignal.dispatchEvent
at AbortSignal.[[[signalAbort]]]
at AbortController.abort
at <anonymous>:2:3
>
If you prefer not to fail the promise, i.e. treat the abort signal as "skip sleep", simply replace the call to ng(aborted) with a call to ok().
I have multiple places where I need to make ajax requests to fetch the items corresponding to some ids. However, I only want to make a single request by accumulating these ids and debouncing the actual method that makes the ajax request...So far I've come up with this code, but it just feels ugly/non-reusable.
Is there any simpler/recommended method to achieve similar results without sharing resolve/promise variables like I did here?
Here's a fiddle
const fakeData = [{
id: 1,
name: 'foo'
},
{
id: 2,
name: 'bar'
},
{
id: 3,
name: 'baz'
}
];
let idsToFetch = [];
let getItemsPromise, resolve, reject;
const fetchItems = _.debounce(() => {
console.log('fetching items...');
const currentResolve = resolve;
const currentReject = reject;
// simulating ajax request
setTimeout(function() {
const result = idsToFetch.map((id) => fakeData.find(item => item.id == id));
currentResolve(result);
}, 400);
getItemsPromise = resolve = reject = null;
}, 500);
function getItems(ids) {
idsToFetch = ids.filter((id) => !idsToFetch.includes(id)).concat(idsToFetch);
if (!getItemsPromise) {
getItemsPromise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
}
fetchItems();
return getItemsPromise
.then((res) => {
return res.filter((item) => ids.includes(item.id));
})
}
setTimeout(() => {
console.log('first request start');
getItems([1]).then(res => console.log('first result:', res));
}, 100);
setTimeout(() => {
console.log('second request start');
getItems([1, 2]).then(res => console.log('second result:', res));
}, 200)
setTimeout(() => {
console.log('third request start');
getItems([1, 3]).then(res => console.log('third result:', res));
}, 300)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
I found it simpler to write a debounce() function with behaviour fully under my control rather than rely on a library method.
In particular, I went out of my way to engineer a different debounce behaviour from that in the question, by which (if I understand correctly) the first, and possibly only, request of a quick sequence must wait for the debounce delay to expire.
In the code below, instead of the original getItemsPromise a debouncePromise is used to signify a debounce period, during which fetching is suppressed and request data is allowed to accumulate. From the quiescent state (whenever debouncePromise === null), the next fetch() call will fetch data ASAP (next tick). Only second and subsequent calls are debounced, until the debounce period expires and the debounce() instance returns to its quiescent state. I think that is as valid a "debounce" paradigm as the original, and arguably better. (If not, then fetch() can be lightly modified to give the original behaviour).
Apart from that, differences are minor :
messy externalized resolve and reject are avoided
in an attempt to keep debounce() generic, a resultsFilter function is passed in addition to a fetcher and delay.
Further comments in code.
function debounce(fetcher, resultsFilter, delay) {
let idsToFetch = [],
debouncePromise = null;
function reset() { // utility funtion - keeps code below clean and DRY
let idsToFetch_ = idsToFetch;
idsToFetch = [];
return idsToFetch_;
}
function fetch(ids) {
idsToFetch = idsToFetch.concat(ids.filter(id => !idsToFetch.includes(id))); // swapped around so as not to reverse the order.
if (!debouncePromise) {
// set up the debounce period, and what is to happen when it expires.
debouncePromise = new Promise(resolve => {
setTimeout(resolve, delay);
}).then(() => {
// on expiry of the debounce period ...
debouncePromise = null; // ... return to quiescent state.
return fetcher(reset()); // ... fetch (and deliver) data for all request data accumulated in the debounce period.
});
// *** First call of this debounce period - FETCH IMMEDIATELY ***
return Promise.resolve(reset()).then(fetcher); // (1) ensure fetcher is called asynchronously (as above). (2) resultsFilter is not necessary here.
} else {
return debouncePromise.then(res => resultsFilter(ids, res)); // when debouncePromise exists, return it with chained filter to give only the results for these ids.
}
}
return fetch;
}
Sample usage :
function fetchItems(ids) {
const fakeData = [
{ 'id': 1, 'name': 'foo' },
{ 'id': 2, 'name': 'bar' },
{ 'id': 3, 'name': 'baz' },
{ 'id': 4, 'name': 'zaz' }
];
if (ids.length > 0) {
return new Promise(resolve => { // simulate ajax request
setTimeout(resolve, 400);
}).then(() => {
return ids.map(id => fakeData.find(item => item.id == id));
});
} else {
return Promise.resolve([]);
}
}
function filterResults(ids, results) {
return results.filter(item => ids.includes(item.id));
}
// ******************************************************
let getItems = debounce(fetchItems, filterResults, 500);
// ******************************************************
setTimeout(() => {
console.log('first request start');
getItems([1]).then(res => console.log('first result:', res));
}, 100);
setTimeout(() => {
console.log('second request start');
getItems([1, 2]).then(res => console.log('second result:', res));
}, 200);
setTimeout(() => {
console.log('third request start');
getItems([1, 3]).then(res => console.log('third result:', res));
}, 300);
setTimeout(() => {
console.log('fourth request start');
getItems([1, 4]).then(res => console.log('fourth result:', res));
}, 2000);
Tested to the extent of this fiddle
I was able to somehow encapsulate the logic by creating a function generator that holds the previous two functions like this:
const fakeData = [{
id: 1,
name: 'foo'
},
{
id: 2,
name: 'bar'
},
{
id: 3,
name: 'baz'
}
];
function makeGetter(fetchFunc, debounceTime = 400) {
let idsToFetch = [];
let getItemsPromise, resolve, reject;
const fetchItems = _.debounce(() => {
console.log('fetching items...');
const currentResolve = resolve;
const currentReject = reject;
const currentIdsToFetch = idsToFetch;
Promise.resolve(fetchFunc(currentIdsToFetch))
.then(res => currentResolve(res))
.catch(err => currentReject(err));
getItemsPromise = resolve = reject = null;
idsToFetch = [];
}, debounceTime);
const getItems = (ids) => {
idsToFetch = ids.filter((id) => !idsToFetch.includes(id)).concat(idsToFetch);
if (!getItemsPromise) {
getItemsPromise = new Promise((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
}
const currentPromise = getItemsPromise;
fetchItems();
return currentPromise
.then((res) => {
return res.filter((item) => ids.includes(item.id));
})
}
return getItems;
}
const getItems = makeGetter((ids) => {
// simulating ajax request
return new Promise((resolve, reject) => {
setTimeout(function() {
const result = ids.map((id) => fakeData.find(item => item.id == id));
resolve(result);
}, 400);
})
});
setTimeout(() => {
console.log('first request start');
getItems([1]).then(res => console.log('first result:', res));
}, 100);
setTimeout(() => {
console.log('second request start');
getItems([1, 2]).then(res => console.log('second result:', res));
}, 200)
setTimeout(() => {
console.log('third request start');
getItems([1, 3]).then(res => console.log('third result:', res));
}, 300)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>