Last active
January 3, 2016 00:39
-
-
Save grifdail/8383944 to your computer and use it in GitHub Desktop.
callbackToPromise
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
| function callbackToPromise(callback) { | |
| return function() { | |
| var arg = arguments | |
| return new Promise(function(succed, reject) { | |
| arg.push(function(err, result) { | |
| if (err) return reject(err);//Si il y a eu une erreure, on rejete la promesse. | |
| if(arguments.length>2) { //Si il y a plus de 2 valeur retourné au callback, on renvoie un array. | |
| result = arguments.splice(0,1); | |
| } | |
| succed(result); | |
| }) | |
| callback.apply(null,arg) | |
| }) | |
| } | |
| } | |
| /* | |
| var readFile = callbackToPromise(fs.readFile); | |
| readFile("gdp.json").then(JSON.parse).then(console.log, console.error); | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment