Created
November 14, 2015 07:25
-
-
Save nsisodiya/53ce1efffc5e56f88f9b to your computer and use it in GitHub Desktop.
convert a callback-style node method to promise
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
| var User = { | |
| getData: function(userId, cb){ | |
| AsyncDB.query("GET DATA FOR userId", function(err, data){ | |
| cb(err, data); | |
| }); | |
| } | |
| }; | |
| promisify(User, 'getData');// This will append method called `getDataAsync` | |
| User.getDataAsync('23ss23').then(function(data){ | |
| console.log('User data is ' + data); | |
| }).fail(function(err){ | |
| console.error(err); | |
| }); | |
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
| var promisify = function (API, methodName) { | |
| API[methodName + 'Async'] = function () { | |
| var gen = {}; | |
| var promise$ = new Promise(function (resolve, reject) { | |
| gen.resolve = resolve; | |
| gen.reject = reject; | |
| }); | |
| var allArgs = Array.prototype.slice.call(arguments); | |
| allArgs.push(function (err, data) { | |
| if (err) { | |
| gen.reject(err); | |
| return; | |
| } | |
| gen.resolve(data); | |
| }); | |
| API[methodName].apply(API, allArgs); | |
| return promise$; | |
| }; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment