94
fetch() {   
    return axios.get('/rest/foo')
        //.then(response => {throw new Error(response)}) // Uncomment to test network error
        //.then( <<add delay here>> ) // Uncomment to simulate network delay
}

How do I add delay in the latter then block, so it will wait specified amount of time before passing control to the fetch callers then blocks?

Tuomas Toivonen
  • 21,690
  • 47
  • 129
  • 225

2 Answers2

213

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(...)
  • 4
    Thanks for this solution, worked well for me with a minor modification for my case: within an async function, you can just write: `await new Promise(resolve => setTimeout(resolve, 1000))` – jsaven Jul 13 '19 at 10:23
  • 2
    Starting from Node.js 16, you can also use the [Timers Promises API](https://nodejs.org/api/timers.html#timers_timers_promises_api). – Curious Sam Dec 09 '21 at 11:45
22

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));
}
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 6
    With TypeScript typings: `function wait(ms: number, value: T) { return new Promise((resolve) => setTimeout(resolve, ms, value)); }` – MEMark May 22 '20 at 09:52