Skip to content
PhoenixGrey0108 edited this page Dec 28, 2012 · 21 revisions

PromiseJs

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:

  1. fs.readFile(filename, read_callback)
  2. encrypt(data, encrypt_callback)
  3. 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);
};

Clone this wiki locally