How to add delay to promise inside then
Return a promise from the then
handler that waits:
.then(() => new Promise(resolve => setTimeout(resolve, 1000)))
If you want to "pass through" the value of the promise, then
.then(x => new Promise(resolve => setTimeout(() => resolve(x), 1000)))
To avoid this boilerplate everywhere, write a utility function:
function sleeper(ms) {
return function(x) {
return new Promise(resolve => setTimeout(() => resolve(x), ms));
};
}
then use it as in
.then(sleeper(1000)).then(...)
This is one of the rare situations you create a new promise:
fetch() {
return axios.get('/rest/foo')
.then(value => new Promise(resolve => {
setTimeout(() => {
resolve(value);
}, delayInMilliseconds);
})
);
}
But rather than a one-off, I'd have (in fact, do have) a utility function:
function wait(ms, value) {
return new Promise(resolve => setTimeout(resolve, ms, value));
}
Then:
fetch() {
return axios.get('/rest/foo')
.then(value => wait(delayInMilliseconds, value));
}
Here's wait
with TypeScript types (thanks MEMark!):
function wait<T>(ms: number, value: T) {
return new Promise<T>((resolve) => setTimeout(resolve, ms, value));
}