延迟连锁承诺 [英] Delay chained promise

查看:66
本文介绍了延迟连锁承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行以下操作,但是它不起作用.如何调整代码使其在.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);
});

推荐答案

您可以创建一个简单的延迟函数,该函数返回一个promise并将其用于您的promise链:

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)已经内置了).请注意,此版本的延迟传递给链中下一个链接的值:


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

这篇关于延迟连锁承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆