Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add delay to promise inside then [duplicate]

People also ask

How do you add a delay in promise?

The built-in function setTimeout uses callbacks. Create a promise-based alternative. function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } delay(3000).

Can we write promise Inside promise?

Here we need to first declare a Promise by using the Promise syntax, and we will be using the then() method for its execution and then inside that then() method we will create another promise by using the same Promise syntax as illustrated above, and then we will call our result of first inside that new Promise.

How do you delay a function in Javascript?

To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds. arg1, arg2, arg3 − These are the arguments passed to the function.

Why promise is executed before setTimeout?

The reason the promise is executing before your timeout is that the promise isn't actually waiting for anything so it resolved right away. @frankies That has more to do with the way Promises are queued and resolved. The focus of my answer is the difference between setTimeout and Promise .


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));
}