I\'m having a function returning a promise. In this function, we call a third party vender to send some push notification through their server.
it looks like
Insert another promise in the chain which delays the next one:
apiGetLoggedInUser
.then(user => {
return new Promise(resolve => setTimeout(() => resolve(user), 3000));
})
.then(user => sendMessage(user.name))
The short version:
function wait(milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds));
}
Example:
async function myFunc(user) {
await wait(3000);
sendMessage(user.name);
}
A different approach - useful if you want to do this sort of thing in many places
This bit is done once
Promise.prototype.thenWait = function thenWait(time) {
return this.then(result => new Promise(resolve => setTimeout(resolve, time, result)));
};
Then you can use it, like this usage for your example, anywhere
apiGetLoggedInUser.thenWait(3000).then(user => sendMessage(user.name));
Create new promise which will call sendMessage
after a timeout.
apiGetLoggedInUser.then(
user => {
return new Promise((resolve, reject) => {
setTimeout(() => {
sendMessage(user.name).then(resolve, reject);
}, 3000)
});
}
)