Skip to content

Instantly share code, notes, and snippets.

@vernak2539
Last active November 10, 2015 20:42
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 vernak2539/a565f84bf6a7d583eaaa to your computer and use it in GitHub Desktop.
Save vernak2539/a565f84bf6a7d583eaaa to your computer and use it in GitHub Desktop.
Promises and Callbacks
'use strict';
var TestConstructor = require('./test-module');
var Testing = new TestConstructor();
Testing.doSomething(function(err, data) {
// oh im done. an async process has happened
});
'use strict';
var TestConstructor = require('./test-module');
var Testing = new TestConstructor();
Testing.doSomething()
.then(function(data) {
// oh im done. an async process was successful
})
.catch(function(err) {
// oh shit, something went wrong
})
.then(function(data) {
// do something else, which would usually go in a callback
});
var Promise = (typeof Promise === 'undefined') ? require('bluebird') : Promise;
'use strict';
var Test = function() {};
Test.prototype.doSomething = function(callback) {
// set up
// do some more stuff
// lets execute the callback
if(typeof callback === 'function') {
return this.asyncProcess(callback);
}
// whoops, no callback. assume promises
return new Promise(function(resolve, reject) {
this.asyncProcess(function() {
if(err) {
return reject(err);
}
resolve(data);
});
}.bind(this));
};
module.exports = Test;
'use strict';
var Test = function() {};
Test.prototype.doSomething = function(callback) {
// set up
// do some more stuff
// execute an async function, which will then
// call your callback when done
this.asyncProcess(callback);
};
module.exports = Test;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment