How can we delay execution of the next promise in a chain?

javascript-promises

A simple way to implement a delay promise that will delay the execution of the next promise in the chain. A current project I am working on requires me to handle request-limits of an API. If requesting too many requests per minute/hour/day/decade, the API sends a "Limits Exceeded" error, with the amount of time I need to wait before making another request.

Since I am working with promises, I wanted a simple way to delay the execution of the next task, and came up with this simple solution. The DelayPromise. I was trying to find a way to constantly delay the tasks (API requests) execution, while having the possibility to change the time between tasks dynamically.

What The DelayPromise practically does is take the result from the last promise, wait N milliseconds and resolve. Very simple and very efficient (in my case, at least). Here is the code:

function DelayPromise(delay) {  
  //return a function that accepts a single variable
  return function(data) {
    //this function returns a promise.
    return new Promise(function(resolve, reject) {
      setTimeout(function() {
        //a promise that is resolved after "delay" milliseconds with the data provided
        resolve(data);
      }, delay);
    });
  }
}

Here is a simple usage scenario:

//define a promise that does... something. Just for the demo, of course.
var promise = new Promise(function(resolve, reject) {  
  resolve("yei!");
});

promise.then(DelayPromise(1000)).then(function(data) {  
  //outputs "yei!" after one second.
  console.log(data) 
});
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License