Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

javascript - Delay chained promise

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);
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...