Created
October 1, 2016 23:16
-
-
Save colceagus/697074f3414e8e71c70dfbd1fbcc7617 to your computer and use it in GitHub Desktop.
Example of function with callback that returns a promise. Can use both promise chaining and callback.
This file contains 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
'use strict'; | |
var q = require('q'); | |
function promisifyme(value, callback) { | |
var deferred = q.defer(); | |
if (value === 3) { | |
deferred.resolve(123); | |
} | |
if (value === 5) { | |
deferred.reject(new Error("321")); | |
} | |
deferred.resolve(333); | |
deferred.promise.nodeify(callback); | |
return deferred.promise; | |
}; | |
promisifyme(3).then(function (result) { | |
console.log('he promised me first and he did it!'); | |
}).catch(function (err) { | |
console.log('he promised me first, but something wrong happened and he brought me ' + err); | |
}); | |
promisifyme(5).then(function (result) { | |
console.log('he promised me first and he did it!'); | |
}).catch(function (err) { | |
console.log('he promised me first, but something wrong happened and he brought me ' + err); | |
}); | |
promisifyme(3, function (err, result) { | |
if (err) { | |
return console.log('He called the callback with an error!'); | |
} | |
console.log('He called the callback with the result of ' + result); | |
}); | |
promisifyme(5, function (err, result) { | |
if (err) { | |
return console.log('He called the callback with ' + err); | |
} | |
console.log('He called the callback with the result of ' + result); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment