javascript - Is this the correct way to wrap readFileSync in a Promise -


the reason below code rid of callback hell/pyramid of doom. don't understand i/o blocking though yet.

'use strict';  var fs = require('fs'); var co = require('co');  co(function* () {      var filename = 'readme.txt';      var str =         yield new promise(function (resolve, reject) {             var result;             try {                 result = fs.readfilesync(filename, 'utf8');             } catch (err) {                 reject(err);             }             resolve(result);         });     console.log('result readfilesync: ' + str);  }); 

all i'm expecting yes or no answer honest. hope if no give details i'm trying learn javascript sync/async , how harness power of promises.

short answer

no

useful answer

if want wrap file read operation, try use async versions of node functions as possible. using readfilesync promise gives no advantage on using readfilesync on own, because readfilesync blocks process until done reading, readfile not.

a better solution therefore this:

'use strict';  var fs = require('fs');  var readfilepromise = function(file) {   return new promise(function(ok, notok) {     fs.readfile(file, function(err, data) {         if (err) {           notok(err)         } else {           ok(data)         }     })   }) }  readfilepromise('/etc/passwd').then(function(data) {   // data... }) 

Comments