07_05_GuyT
07_05_GuyT

Reputation: 2887

Convert async code to promise

I use the following code and I need to convert it to promise and at the end return object which contain the file configuration, how should I do that ?

 var Promise = require('bluebird'),
      glob = promisifyAll(require("glob")),
      fs = Promise.promisifyAll(require("fs"));

module.exports = {
    parse: function (configErr) {
    glob("folder/*.json", function (err, files) {
      if (err) {
        return configErr(new Error("Error to read json files: " + err));
      }
      files.forEach(function (file) {
        fs.readFileAsync(file, 'utf8', function (err, data) { // Read each file
          if (err) {
            return configErr(new Error("Error to read config" + err));
          }
          return JSON.parse(data);
        });
      })
    })

UPDATE -in the code I want to get json files from specific folder in my node project and parse the json content to object

Upvotes: 2

Views: 1660

Answers (1)

Bergi
Bergi

Reputation: 664548

Promisified functions return promises, you should use those instead of passing callbacks into the invocation. Btw, your forEach loop does not work asynchronously, you should use a dedicated promise function for that.

 var Promise = require('bluebird'),
     globAsync = Promise.promisify(require("glob")),
     fs = Promise.promisifyAll(require("fs"));

module.exports.parse = function() {
    return globAsync("folder/*.json").catch(function(err) {
        throw new Error("Error to read json files: " + err);
    }).map(function(file) {
        return fs.readFileAsync(file, 'utf8').then(JSON.parse, function(err) {
            throw new Error("Error to read config ("+file+")" + err);
        });
    });
};

Then you can import this promise, and catch errors or use the array of parsed config objects by attaching callbacks to it via .then.

var config = require('config');
config.parse().then(function(cfg) { … }, function onConfigErr(err) { … })

Upvotes: 3

Related Questions