How to add delay to promise inside then

Tuomas Toivonen picture Tuomas Toivonen · Aug 15, 2016 · Viewed 60.3k times · Source
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?

Answer

user663031 picture user663031 · Aug 15, 2016

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(...)