Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

javascript - Call to modules in specific order in node

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);

Update

this is the 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 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);
                        }
                    })
                });
            });
        });
    }
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Because glob and fs.readFile are async functions and appHandler.invokeAction is invoked during i/o from disk.

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);
});

and for validate

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
        });
      }));
    })
  }
};

If you want working with promise mz could help :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...