Created
October 27, 2015 14:51
-
-
Save amireh/a31d56b8c638be81c3e1 to your computer and use it in GitHub Desktop.
Shows how to build a controllable RSVP promise queue that you can flush at any point to run all pending Promise callbacks.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This code assumes you're not using any module loader, and that | |
// Ember is available on `window`. Tune accordingly if you are | |
// using a module loader. | |
var Ember = window.Ember; | |
var RSVP = Ember.RSVP; | |
var Backburner; | |
var queue; // our backburner queue | |
// here we tell RSVP to let us queue the promise callbacks | |
// ourselves. This will be called anytime you use `then()` | |
// or dispatch a promise (like new RSVP.Promise, or RSVP.defer()) | |
RSVP.configure('async', function(callback, promise) { | |
queue.defer('promises', promise, callback, promise); | |
}); | |
// We need to get a handle on the Backburner object, which Ember buries | |
// deeply in its loaded modules, but there's a hack to get to it. | |
// | |
// Do this once for all tests. If you use mocha or Jasmine you can use an | |
// async global "before()" block like this: | |
before(function(done) { | |
Ember.__loader.define("setupRSVP", ["backburner"], function(exports) { | |
Backburner = exports.default; | |
done(); | |
}); | |
Ember.__loader.require("setupRSVP"); | |
}); | |
// Again, if you're using mocha or Jasmine this will do. | |
// | |
// We launch a new queue for every test which we can | |
// flush as needed later. | |
beforeEach(function startCollectingPromises() { | |
queue = new Backburner(['promises']); | |
queue.begin(); | |
}); | |
// Flush any pending promises by invoking their fulfillment handlers. | |
// | |
// Export this somehow (like `window.flushPromiseQueue = flush`) | |
// and now you can use it as such: | |
// | |
// describe('my suite', function() { | |
// it('dispatches a promise', function(done) { | |
// doSomethingAsync().then(function(yieldedValue) { | |
// assert(yieldedValue == 5); // or whatever | |
// | |
// done(); | |
// }); | |
// | |
// window.flushPromiseQueue(); | |
// }); | |
// }); | |
// | |
function flush() { | |
queue.end(); | |
queue.begin(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment