Skip to content

Instantly share code, notes, and snippets.

@juandopazo
Created May 12, 2011 13:30
Show Gist options
  • Select an option

  • Save juandopazo/968484 to your computer and use it in GitHub Desktop.

Select an option

Save juandopazo/968484 to your computer and use it in GitHub Desktop.
Differences between AsyncQueue and Deferreds
/*
IIRC AsyncQueue is designed for splitting cpu intensive code into chunks and run them sequentially separated by small timeouts.
Deferreds are a way of rewriting async calls without callbacks or events. They are probably more useful in Node.js.
For example, when normally you'd get a lot of callbacks connecting to a db...
*/
mysql_connect('user', 'pwd', function (err) {
if (err) throw new err;
mysql_open_database('myDatabase', function (err) {
if (err) throw new err;
mysql_query('SELECT * FROM table', function (err, result) {
if (err) throw new err;
/* do something */
});
});
});
/*
...using a class that uses Deferred you could write:
*/
var db = new MySQL({
user: 'user',
pwd: 'password'
});
db.connect().open('myDatabase').query('SELECT * FROM table').then(function (result) {
/* do something */
});
/*
With something like this as a MySQL class
*/
var MySQL = Y.Base.create('mysql', Y.Base, [Y.Deferred], {
ATTRS: {
user: {},
pwd: {},
database: {}
}
}, {
_next: function (promise, err) {
var args = SLICE.call(arguments, 2);
if (err) {
promise.rejectWith(this, args);
} else {
promise.resolveWith(this, args);
}
},
connect: function () {
return this.promise(function (p) {
mysql_connect(this.get('user'), this.get('pwd'), Y.bind(this._next, this, p));
});
},
open: function (db) {
return this.promise(function (p) {
mysql_open_database(db || this.get('database'), Y.bind(this._next, this, p));
});
},
query: function (query) {
return this.promise(function (p) {
mysql_query(query, Y.bind(this._next, this, p));
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment