最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin8浏览0评论

The reason for the below code is to get rid of callback hell/pyramid of doom. I don't fully 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 is a yes or no answer to be honest. Hope fully if no could someone give some details as I'm trying to learn properly about JavaScript sync/async and how to harness the power of Promises.

The reason for the below code is to get rid of callback hell/pyramid of doom. I don't fully 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 is a yes or no answer to be honest. Hope fully if no could someone give some details as I'm trying to learn properly about JavaScript sync/async and how to harness the power of Promises.

Share Improve this question edited Jan 24, 2016 at 19:52 basickarl asked Jan 24, 2016 at 19:44 basickarlbasickarl 40.5k69 gold badges237 silver badges354 bronze badges 4
  • 2 Why in the world would you try to wrap a promise around rs.readFileSync()? If you want async, use fs.readFile(). – jfriend00 Commented Jan 24, 2016 at 19:48
  • @jfriend00 Ever heard of callback hell/pyramid of doom? Go check it! – basickarl Commented Jan 24, 2016 at 19:49
  • @KarlMorrison - Where is your callback function? – Amit Commented Jan 24, 2016 at 19:50
  • 1 fs.readFileSync does not need callbacks at all. It's synchronous. There is no callback hell with fs.readfileSync(). I'm thinking that maybe you meant to ask about fs.readFile() which IS asynchronous and does involve callbacks. – jfriend00 Commented Jan 24, 2016 at 19:56
Add a ment  | 

2 Answers 2

Reset to default 11

Short answer

No

Useful answer

If you want to wrap a file read operation, try to use the async versions of Node functions as much as possible. Using readFileSync with a promise gives you no advantage over using readFileSync on its own, because readFileSync blocks the process until it is done reading, which readFile does not.

A better solution would therefore be something like 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) {
  // do something with the data...
})

The correct way is to use the Node's native util library and promisfy fs.readFile:

const path = require('path');
const fs = require('fs');

const INDEX = path.join(__dirname, 'app', 'index.html');
const readFile = require('util').promisify(fs.readFile);

readFile(INDEX)
  .then(e => console.log(e.toString()))
  .catch(e => console.log('FOOBAR ' + e));

result:

one@dolphin:~/github/resume $ node toolchain/inject.js 
FOOBAR Error: ENOENT: no such file or directory, open '/home/one/github/resume/toolchain/app/index.html'
发布评论

评论列表(0)

  1. 暂无评论