Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...