Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...