-
Notifications
You must be signed in to change notification settings - Fork 3
PromiseJs
PhoenixGrey0108 edited this page Dec 28, 2012
·
21 revisions
Once you work with Nodejs, you will write a lot of asynchronous code by callback functions. Using callback-passing for asynchronous actions does not compose very well and might create complex flows of passing callbacks around to handle return values. We are here making a simple example to see the reason why we use PromiseJs.
The task is to read content from a file, then encrypt it, then write it to the file.
Therefore, there are three functions to be applied:
- fs.readFile(filename, read_callback)
- encrypt(data, encrypt_callback)
- fs.writeFile(filename, content, write_callback)
We can define the simplest encrypt function as
var fs = require('fs');
var encrypt = function(data, callback) {
var encrypted_data = "";
len = data.length;
console.log(len);
for(var i=0; i<len; i++) {
encrypted_data += String.fromCharCode((data[i].charCodeAt()+1)%128);
}
return callback(null, encrypted_data);
};