Even though RSVP provides a denodeify
API, lie-denodify's main focus is to turn a node style callback into a promise based one.
lie-denofiy internally uses lie which is a basic but performanent promise implementation.
All it does to convert an async function to a promise based one is to return a promise with the help of lie:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| var promise = require('lie');
function denodify(func) {
return function() {
var args = Array.prototype.concat.apply([], arguments);
return promise(function(resolve, reject) {
args.push(function(err, success) {
if (err) {
reject(err);
}
else {
resolve(success);
}
});
func.apply(undefined, args);
});
};
}
module.exports = denodify;
|
Installation: npm install lie-denodify
Usage example:
Let's try and covert fs.stat
function to a promise!
First of all let's have a look at how fs.stat
works before conversion.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| var fstat = require('fs').stat;
fstat('/tmp',function(err,res){
if(!err){
console.log(res);
} else {
throw new Error(err);
}
});
/*
Would log something like:
{ dev: 16777217,
mode: 17407,
nlink: 14,
uid: 0,
gid: 0,
rdev: 0,
blksize: 4096,
ino: 144575596,
size: 476,
blocks: 0,
atime: Thu Apr 10 2014 17:38:18 GMT+0530 (IST),
mtime: Thu Apr 10 2014 17:51:50 GMT+0530 (IST),
ctime: Thu Apr 10 2014 17:51:50 GMT+0530 (IST) }
And in case of an Error it would throw an error
*/
|
Now, let's convert it into a promise:
1
2
3
4
5
| var lieDndfy = require('lie-denodify');
var statp = lieDndfy ( require('fs').stat );
statp('/tmp').then(console.log,console.error);
|
GIF FTW!
Thanks to Calvin Metcalf the author of lie and lie-denofiy.
Learn to lie this week ;)!