javascript - 如何与其他异步模块一起使用 async?

标签 javascript node.js asynchronous fs

这是一个没有异步的工作测试程序:

var fs = require('fs');
function test() {
    var finalResponse = '', response = '';
    function showFinalResponse() {
        console.log(finalResponse);
    }
    function processTheFile(err, data) {
        if (err) {
            finalResponse = 'Could not read the file';
        } else {
            response += data;
            response += '</body></html>';
            finalResponse = response;
        }
        showFinalResponse();
    }
    function readTheFile(exists) {
        if (!exists) {
            finalResponse = 'File does not exist.';
            showFinalResponse();
        } else {
            response += '<!DOCTYPE html><html lang="en-US"><head></head><body>';
            fs.readFile('file.txt', 'utf8', processTheFile);
        }
    }
    fs.exists('file.txt', readTheFile);
};
test();

这是我尝试让同一个程序与异步 waterfall 一起工作的尝试。我在如何在异步和 fs 调用中传递回调时遇到了问题。

var fs = require('fs');
var async = require('async');
function testAsync() {var finalResponse, response = '';
    async.waterfall( [
        function checkIfTheFileExists(done) {
            fs.exists('file.txt', done);
        },
        function readTheFile(err, exists, done) {
            response += '<!DOCTYPE html><html lang="en-US"><head></head><body>';
            fs.readFile('file.txt', 'utf8', done);
        },
        function processTheFile(err, data, done) {
            response += data;
            response += '</body></html>';
            finalResponse = response;
            done(null);
        } ],
        function showFinalResponse(err) {
            if (err) {
                if (err.code === 'ENOENT') {  // intended to test for file is missing.
                    finalResponse = 'File does not exist.';
                } else { // any other errors.
                    finalResponse = 'Could not read the file';
                }
                console.log(err);
            }
            console.log(finalResponse);
        }
    );
}
testAsync()

我无法让异步版本工作。我对回调的去向感到困惑。

最佳答案

fs.exists 是一个奇怪的地方,因为它不向其回调函数提供错误参数。相反,它只提供一个 exists 参数来指示文件是否已找到。据推测,如果出现错误,exists 将为 false。因此,您需要将其回调包装在您自己的函数中,以便您可以为 waterfall 回调提供一个单独的错误参数:

async.waterfall( [
    function checkIfFileExists(done) {
        fs.exists('file.txt', function(exists) { done(null, exists); });
    },
    function makeSureFileExists(exists, done) {
    ...

注意 the docs 中的警告,但是,通常不应使用 fs.exists

关于javascript - 如何与其他异步模块一起使用 async?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23412728/

相关文章:

node.js - 解密 aws kms key 时出现 Nodejs 异步问题

python-3.x - 使用 Python asyncio 从同步函数中运行并等待异步函数

javascript - 实现上一页和下一页逻辑的最佳方法是什么

javascript - 时刻JS ("Must to show days in next week")

javascript - HTML5 ondrop 事件在 zip.js 完成操作之前返回

http - 使用 NodeJS 流式传输 Http 响应

node.js - res.format() 在 Express 4.x 中不起作用

javascript - 将大型 Base64 字符串发布到服务器

javascript - 单击图像时清除文本框中的内容

javascript - 设置内容类型 : in angular js post request