Convert async code to promise

自古美人都是妖i 提交于 2019-12-06 08:16:02

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) { … })
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!