viernes, 25 de diciembre de 2015

Playing with promises in javascript

Reading about callbacks, monads, ... I've tried q library.
Interesting reading about monads and promises, source

This the code.

var fs = require('fs');
var Q = require('q');

function readFile(file){
  var deferred = Q.defer();
  fs.readFile(file, 'utf8', function (err, data) {
    if (err){
   deferred.reject(err);
 } 
    else{
   deferred.resolve(data);
 }
  });
  return deferred.promise;
}

var textFilteContent = readFile('notes.txt');

textFilteContent.then(function(data){
 console.log(data);
}).fail(function(err){
 console.log('error reading the file: ', err);
});

console.log('end');

No hay comentarios:

Publicar un comentario