Skip to content

Instantly share code, notes, and snippets.

@benshimmin
Last active April 6, 2016 09:55
Show Gist options
  • Save benshimmin/6508598 to your computer and use it in GitHub Desktop.
Save benshimmin/6508598 to your computer and use it in GitHub Desktop.
Asychronous queues with RequireJS and JavaScript (and no yucky promises)
// Sometimes you care about the order in which RequireJS-loaded modules
// are retrieved, and wish to execute a callback for each module in the
// order in which you originally specified them, rather than the order
// in which they are loaded. You can do this with a queue.
var Queue = function() {
var q,
callCount = 0;
function Queue() {
q = [];
this.callback = undefined;
}
Queue.prototype.add = function(obj) {
return q.push({
loaded : {},
data : obj
});
};
Queue.prototype.resolve = function(pos, loaded) {
q[pos - 1].loaded = loaded;
if (++callCount === q.length) {
while (q.length) this.execute(q.shift());
}
};
Queue.prototype.execute = function(queued) {
this.callback(queued.loaded, queued.data);
};
return new Queue();
};
// usage:
var queue;
// a dummy Backbone view, but this could of course be anything
var View = Backbone.View.extend({
initialize : function() {
// create a new Queue
queue = new Queue();
// add a callback *for each thing loaded*
queue.callback = this.renderView;
// load 5 fake views
_.times(5, function() {
this.load({
type : "some-test-view"
});
}, this);
},
load : function(data) {
// add the data to the queue, returning its
// position in the queue
var pos = queue.add(data);
require(["views/" + data.type], function(view) {
// when the item has loaded, tell the queue,
// passing it the queue position and the loaded
// item (`view`)
queue.resolve(pos, view);
});
},
renderView : function(view, data) {
view.render(data);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment