延迟链式承诺 [英] Delay chained promise
本文介绍了延迟链式承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试执行以下操作,但它不起作用.如何调整代码以在 .then
和 .done
之间有延迟?
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
?
myService.new(a).then(function (temp) {
setTimeout(function () {
return myService.get(a, temp);
}, 60000);
}).done(function (b) {
console.log(b);
});
推荐答案
您可以创建一个简单的延迟函数来返回一个承诺并在您的承诺链中使用它:
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);
});
<小时>
您还可以使用 .delay()
方法来扩充 Promise
原型(某些像 Bluebird 这样的 Promise 库已经内置了该方法).请注意,此版本的延迟将传递给链中下一个链接的值:
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);
});
}
然后,你可以这样做:
myService.new(a).delay(60000).then(function(temp) {
return myService.get(a, temp);
}).then(function (b) {
console.log(b);
});
这篇关于延迟链式承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文