Skip to content

Instantly share code, notes, and snippets.

@GavinJoyce
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GavinJoyce/54c03bd4048a8f64742e to your computer and use it in GitHub Desktop.
Save GavinJoyce/54c03bd4048a8f64742e to your computer and use it in GitHub Desktop.
Simple spike of an incremental backoff for Ember.js
// **EDIT**: I've created an ember-cli addon for this here:
//
// https://github.com/GavinJoyce/ember-backoff
var delay = function(milliseconds) {
milliseconds = milliseconds || 2000;
return new Em.RSVP.Promise(function(resolve) {
Em.run.later(this, function() {
resolve();
}, milliseconds);
});
};
var retryWithBackoff = function(callback, retryCountBeforeFailure, waitInMilliseconds) {
if(Em.empty(retryCountBeforeFailure)) {
retryCountBeforeFailure = 5;
}
waitInMilliseconds = waitInMilliseconds || 250;
return callback().catch(function(reason) {
if (retryCountBeforeFailure-- > 1) {
waitInMilliseconds = waitInMilliseconds * 2;
return delay(waitInMilliseconds).then(function() {
return retryWithBackoff(callback, retryCountBeforeFailure, waitInMilliseconds);
});
}
throw reason;
});
}
@GavinJoyce
Copy link
Author

import Em from 'ember';

var delay = function(milliseconds) {
  milliseconds = milliseconds || 2000;
  return new Em.RSVP.Promise(function(resolve) {
    Em.run.later(this, function() {
      resolve();
    }, milliseconds);
  });
};


var retryWithBackoff = function(callback, retryCountBeforeFailure, waitInMilliseconds) {
  console.log('retryWithBackoff');
  if(Em.empty(retryCountBeforeFailure)) {
    retryCountBeforeFailure = 5;
  }
  waitInMilliseconds = waitInMilliseconds || 250;

  return callback().catch(function(reason) {
    if (retryCountBeforeFailure-- > 1) {
      waitInMilliseconds = waitInMilliseconds * 2;

      return delay(waitInMilliseconds).then(function() {
        return retryWithBackoff(callback, retryCountBeforeFailure, waitInMilliseconds);
      });
    }

    throw reason;
  });
};

var withBackoff = function(context, method) {
  var args = Array.prototype.slice.call(arguments, 2);
  var callback = context[method];
  return retryWithBackoff(function() {
    return callback.apply(context, args);
  });
};

export default Em.Route.extend({
  queryParams: {
    page: {
      refreshModel: true
    }
  },
  model: function(params) {
    return withBackoff(this.store, 'find', 'user', {
      page: params.page
    });
  }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment