I\'m trying to do the following but it isn\'t working. How can I adjust the code to have a delay between .then
and .done
?
myServi
You can create a simple delay function that returns a promise and use that in your promise chain:
function delay(t, val) {
return new Promise(function(resolve) {
setTimeout(function() {
resolve(val);
}, t);
});
}
myService.new(a).then(function(temp) {
return delay(60000, temp);
}).then(function(temp) {
return myService.get(a, temp);
}).then(function (b) {
console.log(b);
});
You could also augment the Promise
prototype with a .delay()
method (which some promise libraries like Bluebird already have built-in). Note, this version of delay passes on the value that it is given to the next link in the chain:
Promise.prototype.delay = function(t) {
return this.then(function(val) {
return delay(t, val);
});
}
Then, you could just do this:
myService.new(a).delay(60000).then(function(temp) {
return myService.get(a, temp);
}).then(function (b) {
console.log(b);
});
You can create a .delay()
function set at Promise.prototype
which returns a new Promise
having value of original promise.
Promise.prototype.delay = function(t) {
return this.then(function(data) {
return new Promise(function(resolve) {
setTimeout(resolve, t || 0, data);
})
})
};
Promise.resolve(123)
.delay(6000)
.then(function(data) {
console.log(data)
});
A slightly improved version of jfriend00's approach avoids needing the pass the resolved value like this:
function delay(t) {
return (val) => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(val), t)
})
}
}
can be used like this:
myService.new(a)
.then(delay(60000))
.then(function(temp) {
return myService.get(a, temp);
}).then(function (b) {
console.log(b);
});