在节点中以特定顺序调用模块 [英] Call to modules in specific order in node

查看:87
本文介绍了在节点中以特定顺序调用模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用以下代码调用了两个模块,但是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);
                        }
                    })
                });
            });
        });
    }
};

推荐答案

因为globfs.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆