How to add a delay to

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 to add a delay in the latter and then block it, so it will wait for the specified period of time before transferring control to the receivers of the sample, and then block it?

+6
source share
2 answers

Return a promise from the then handler, which waits:

 .then(() => new Promise(resolve => setTimeout(resolve, 1000))) 

If you want to "pass" the meaning of a promise, then

 .then(x => new Promise(resolve => setTimeout(() => resolve(x), 1000))) 

To avoid this pattern 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(...) 
+26
source

This is one of the rare situations when you create a new promise:

 fetch() { return axios.get('/rest/foo') .then(value => new Promise(resolve => { setTimeout(() => { resolve(value); }, delayInMilliseconds); }) ); } 

If it is possible that value may be a promise, insert .then(value => Promise.resolve(value)) in the chain:

 fetch() { return axios.get('/rest/foo') .then(value => Promise.resolve(value)) // *** .then(value => new Promise(resolve => { setTimeout(() => { resolve(value); }, delayInMilliseconds); }) ); } 
0
source

All Articles