制作的forEach在JavaScript中异步 [英] Make forEach asynchronous in JavaScript

查看:91
本文介绍了制作的forEach在JavaScript中异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解异步编程Node.js的停滞,但在这个code。

I'm trying to understand the asynchronous programming Node.js but stalled on this code.

此功能在他们的回调函数返回文件的数组目录中:

This function in their callback returns an array of files in a directory:

function openDir(path, callback) {
    path = __dirname + path;
    fs.exists(path, function (exists) {
        if (exists) {
            fs.readdir(path, function (err, files) {
                if (err) {
                    throw err;
                }
                var result = [];
                files.forEach(function (filename, index) {
                    result[index] = filename;
                });
                return callback(result);
            });
        }
    });
}

但是当我使用在 .forEach 异步code,它没有返回值:

But when I use asynchronous code inside.forEach, it returns nothing:

function openDir(path, callback) {
    path = __dirname + path;
    fs.exists(path, function (exists) {
        if (exists) {
            fs.readdir(path, function (err, files) {
                if (err) {
                    throw err;
                }
                var result = [];
                files.forEach(function (filename, index) {
                    fs.stat(path + filename, function (err, stats) {
                        if (err) {
                            throw err;
                        }
                        result[index] = filename;
                    });
                });
                return callback(result);
            });
        }
    });
}

我明白为什么会发生,但不知道如何编写正确的code。

I understand why it happens, but don't understand how to write correct code.

推荐答案

其他答案可能工作得很好,但是它们目前都完全不同的语义从原来的code:他​​们都执行统计并行,而不是按顺序。在的forEach 将启动尽可能多的异步统计操作,因为在文件列表中的文件。这些操作的完成顺序可能相当不错是从列表中的原始顺序不同。这可能会显着影响的错误处理逻辑。

The other answers may work well, but they are currently quite different semantically from the original code: they both execute stats in parallel, rather than sequentially. The forEach will initiate as many asynchronous stats operation as there are files in the list of files. The completion order of those operations may quite well be different from the original order of the list. This may substantially affect the error handling logic.

下面的方法实现了一个状态机,其目的是为执行时统计异步的,但顺序(未经测试):

The following approach implements a state machine, which is aimed to executes stats asynchronously, yet sequentially (untested):

function openDir(path, callback) {
    path = __dirname + path;
    fs.exists(path, function (exists) {
        if (!exists)
            callback(null, null); // node (err, result) convention
        else {
            fs.readdir(path, function (err, files) {
                if (err)
                    callback(err, null); // node (err, result) convention
                else {
                    var results = [];
                    var i = 0;
                    nextStep(); // process the first file (the first step)

                    function nextStep() {
                        if (i >= files.length) // no more files?
                            callback(null, result); // node (err, result) convention
                        else {
                            fs.stat(path + files[i], function (err, stats) {
                                if (err)
                                    callback(err, null); // node (err, result) convention
                                else {
                                    results[i++] = stats;
                                    // proceed to the next file
                                    nextStep();
                                }
                            });
                        }
                    }
                }
            }
        }
    });                   
});

诺言的可能有助于减少著名的金字塔末日像上面。

Promises may help to reduce the nesting level of the famous "Pyramid of Doom" like above.

这篇关于制作的forEach在JavaScript中异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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