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
      }, 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) {  

promise.then(DelayPromise(1000)).then(function(data) {  
  //outputs "yei!" after one second.

That's it! You can play around with it here - http://www.es6fiddle.net/ihn517ax/. I hope some of you finds this helpful. Let me know in the comments :)

Connect with me on Twitter or LinkedIn to continue the discussion.

I'm an IT consultant, full stack developer, husband, and father. On my spare time I am contributing to Babylon.js WebGL game engine and other open source projects.

Berlin, Germany