将异步代码转换为promise [英] Convert async code to promise
问题描述
我使用以下代码,我需要将其转换为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 - 我希望从我的节点项目中的特定文件夹中获取json文件并将json内容解析为对象的代码
UPDATE -in the code I want to get json files from specific folder in my node project and parse the json content to object
推荐答案
Promisified函数返回promises,你应该使用那些而不是将回调传递给调用。顺便说一句,你的 forEach
循环不能异步工作,你应该使用专用承诺函数。
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);
});
});
};
然后你可以导入这个promise,并通过附加回调来捕获错误或使用解析的配置对象数组通过 .then
。
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) { … })
这篇关于将异步代码转换为promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!