javascript - Call to modules in specific order in node -


i've used following code call 2 modules, invoke action called before validate file (i saw in debug). should verify validatefile called before apphandler.invokeaction? should use promise?

var validator = require('../uti/valid').validatefile(); var apphandler = require('../contr/handler'); apphandler.invokeaction(req, res); 

update

this validate file code

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 file", err);                     }                     var obj = json.parse(data);                     obj.action.foreach(function (crud) {                         (var k in crud) {                             if (_inarray(crud[k].path, stack)) {                                  console.log("duplicate founded!" + crud[k].path);                                  break;                             }                             stack.push(crud[k].path);                         }                     })                 });             });         });     } }; 

because glob , fs.readfile async functions , apphandler.invokeaction invoked during i/o disk.

promise solution solve old school callback job.

validator.validatefile().then(function() {   apphandler.invokeaction(req, res); }); 

and validate

var promise = require("bluebird"), // not required if using iojs or running node `--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) {         // return array of promises, if of them         // rejected, validatefile promise rejected         return fs.readfile(file).then(function (content) {           // throw new error(''); if content not valid         });       }));     })   } }; 

if want working promise mz :)


Comments