0

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);
});
Penny Liu
  • 15,447
  • 5
  • 79
  • 98
William Falcon
  • 9,813
  • 14
  • 67
  • 110

3 Answers3

1

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);
});
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

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)
});
guest271314
  • 1
  • 15
  • 104
  • 177
0

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);
  });
thedude
  • 9,388
  • 1
  • 29
  • 30