Node.js模块同步到异步
Node.js module sync to async
我有一个简单的Node.js模块,它获取一个Handlebars模板目录,编译它们,然后导出一个基于它们名称的对象:
'use strict';
var
fs = require('fs'),
path = require('path'),
handlebars = require('handlebars'),
templateDir = __dirname + '/templates/',
templates = {};
fs.readdirSync(templateDir).forEach(function (file) {
templates[path.basename(file, path.extname(file))] =
handlebars.compile(fs.readFileSync(templateDir + file));
});
module.exports = templates;
所以在其他模块中,我可以:
var templates = require('./templates');
templates[SOME_TEMPLATE]({ ... });
不过,我正在努力解决如何异步执行此操作,特别是如何在混合中使用发射器进行导出。
var emitter = require('events').EventEmitter;
module.exports = function (callback) {
emitter.on('templates-compiled', function () {
callback(templates);
});
callback();
};
fs.readdir(templateDir, function (err, files) {
if (!err) {
files.forEach(function (file) {
fs.readFile(templateDir + file, function(err, data) {
if (!err) {
templates[path.basename(file, path.extname(file))] =
handlebars.compile(data);
if (files[files.length - 1] === file) {
emitter.emit('templates-compiled');
}
} else {
}
});
});
} else {
}
});
以下是对上述内容的修改:
var EventEmitter = require('events').EventEmitter;
var path = require('path');
var fs = require('fs');
module.exports = function(dir, callback) {
var emitter = new EventEmitter();
var templates = {};
emitter.on('templates-compiled', function(t) {
callback(null, t);
});
emitter.on('templates-error', function(e) {
callback(e);
});
fs.readdir(dir, function(err, files) {
if (!err) {
files.forEach(function(file) {
fs.readFile(path.join(dir, file), function(err, data) {
if (!err) {
//note: i'm just calling toString() here - do your compile here instead
templates[path.basename(file, path.extname(file))] = data.toString();
if (files[files.length - 1] === file) {
emitter.emit('templates-compiled', templates);
}
} else {
emitter.emit('templates-error', err);
}
});
});
} else {
emitter.emit('templates-error', err);
}
});
};
然而,您可能需要考虑使用q或async来修剪厄运金字塔。
相关文章:
- 异步获取数据使用JavaScript同步获取数据
- javascript函数中的异步与同步.(Node.js)
- strongloop script.js run find in before delete方法:如何同步运行异步方法
- 如何模拟同步ajax调用?(基于异步的同步)
- 为什么同步睡眠功能没有被承诺内异步化
- 如何在异步函数与Deferredjquery之间同步
- 使用模态库从嵌套的异步调用中生成javascript同步代码
- 将数据发布到iframe是同步还是异步
- 节点.js / 续集.js / 快递.js - 如何插入多对多关联?(同步/异步?
- NodeJS中的异步与同步
- javascript如何成为一种同步语言并在浏览器和node.js环境中异步运行
- 如何同步2个异步瀑布
- 异步函数调用是否可以在两个同步语句之间完成
- 脚本和图像是同步加载还是异步加载
- 并行开发同步/阻塞和异步/非阻塞库api的好方法是什么?(JavaScript)
- 同步异步创建的承诺
- 基准测试引发错误的异步与同步代码
- 使用jQuery'管理同步和异步JavaScript函数;s延期
- 异步/同步Javascript
- 纠结于node.js中的异步同步