在节点中以特定顺序调用模块 [英] Call to modules in specific order in node
问题描述
我已经使用以下代码调用了两个模块,但是invoke操作是在验证文件之前调用的(我在调试中看到).如何验证在appHandler.invokeAction
之前调用validateFile
?我应该遵守诺言吗?
I've used the following code to call two modules, but the invoke action is called before the validate file (I saw in debug). What I should do to verify that validateFile
is called before appHandler.invokeAction
? Should I use a promise?
var validator = require('../uti/valid').validateFile();
var appHandler = require('../contr/Handler');
appHandler.invokeAction(req, res);
更新
这是验证文件代码
var called = false;
var glob = require('glob'),
fs = require('fs');
module.exports = {
validateFile: function () {
glob("myfolder/*.json", function (err, files) {
var stack = [];
files.forEach(function (file) {
fs.readFile(file, 'utf8', function (err, data) { // Read each file
if (err) {
console.log("cannot read the file", err);
}
var obj = JSON.parse(data);
obj.action.forEach(function (crud) {
for (var k in crud) {
if (_inArray(crud[k].path, stack)) {
console.log("duplicate founded!" + crud[k].path);
break;
}
stack.push(crud[k].path);
}
})
});
});
});
}
};
推荐答案
因为glob
和fs.readFile
是异步函数,并且在从磁盘进行I/O期间调用了appHandler.invokeAction.
Because glob
and fs.readFile
are async functions and appHandler.invokeAction is invoked during i/o from disk.
Promise是解决此问题的一个很好的解决方案,但是老式的回调可以完成此任务.
Promise is a good solution to solve this but an old school callback could do the job.
validator.validateFile().then(function() {
appHandler.invokeAction(req, res);
});
并进行验证
var Promise = require("bluebird"), // not required if you are using iojs or running node with `--harmony`
glob = require('mz/glob'),
fs = require('mz/fs');
module.exports = {
validateFile: function () {
return glob("myfolder/*.json").then(function(files) {
return Promise.all(files.map(function(file) {
// will return an array of promises, if any of them
// is rejected, validateFile promise will be rejected
return fs.readFile(file).then(function (content) {
// throw new Error(''); if content is not valid
});
}));
})
}
};
如果您想使用诺言 mz 可能会有所帮助:)
If you want working with promise mz could help :)
这篇关于在节点中以特定顺序调用模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!