简体   繁体   English

Node.js中的异步函数

[英]asynchronous function in nodejs

It's just a little question about asynchronous function in nodejs and the good way to create them. 这只是有关nodejs中异步函数以及创建它们的好方法的一个小问题。 the following takes in parameters a repository and an extension name and return the list of the files with the given extension in the given repository 下面的参数接受一个存储库和一个扩展名,并返回给定存储库中具有给定扩展名的文件列表

to run 跑步

$ node app /path/to/some/reposity someExtension

module.js file module.js文件

//modules.js
var fs = require('fs');
var path = require('path');
module.exports = function(dir, ext, callback){
    //do something
    fs.readdir(dir, function(err, data){
        if(err){
            //EDIT
            process.nexTick(function(){
                callback(err);
            });
            //
        }
        if(data){
            var compteur = 0;
            var block = [];
            for(var i =0 ; i < data.length ; i++){
                if(path.extname(data[i]).slice(1) == ext){
                    block[compteur]= data[i];
                    compteur++;
                }
            }
            //EDIT
            process.nextTick(function(){
                callback(null, block);
            });
            //
        }

    });
};

app.js file app.js文件

//app.js
var dir = process.argv[2];
var ext = process.argv[3];
var module = require('./module');

module(dir, ext, function(err, data){
    if(err) { throw err;}
    var dl = data.length;
    for(var i = 0 ; i < dl ; i++){
        console.log(data[i]);
    }
});

I just wanted to know if it's the good way to do things or if there a better one. 我只是想知道这是做事的好方法还是有更好的方法。 Thanks in advance. 提前致谢。

I find this nice tutorial on asynchronous function in NodeJS http://howtonode.org/understanding-process-next-tick 我在NodeJS http://howtonode.org/understanding-process-next-tick中找到了关于异步函数的很好的教程

The standard way to program asynchronously is to use callbacks, which is what you've doing. 异步编程的标准方法是使用回调,这就是您正在做的事情。 Since the callback is nested within an asynchronous function, it will be queued once the callstack is empty. 由于回调嵌套在异步函数中,因此一旦调用堆栈为空,它将被排队。

Also, don't name any variables module . 另外,不要命名任何变量module It is a global variable which should not be overwritten. 它是一个全局变量,不应覆盖。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM