javascript - 在 node.js 中使用异步 waterfall

标签 javascript node.js asynchronous npm

我有 2 个异步运行的函数。我想用 waterfall 模型来写它们。问题是,我不知道如何..

这是我的代码:

var fs = require('fs');
function updateJson(ticker, value) {
  //var stocksJson = JSON.parse(fs.readFileSync("stocktest.json"));
  fs.readFile('stocktest.json', function(error, file) {
    var stocksJson =  JSON.parse(file);

    if (stocksJson[ticker]!=null) {
      console.log(ticker+" price : " + stocksJson[ticker].price);
      console.log("changing the value...")
      stocksJson[ticker].price =  value;

      console.log("Price after the change has been made -- " + stocksJson[ticker].price);
      console.log("printing the the Json.stringify")
      console.log(JSON.stringify(stocksJson, null, 4));
      fs.writeFile('stocktest.json', JSON.stringify(stocksJson, null, 4), function(err) {  
        if(!err) {
          console.log("File successfully written");
        }
        if (err) {
          console.error(err);
        }
      }); //end of writeFile
    } else {
      console.log(ticker + " doesn't exist on the json");
    }
  });
} // end of updateJson 

知道如何使用 waterfall 来编写它,这样我就可以控制它了吗?请给我写一些例子,因为我是 node.js 的新手

最佳答案

首先确定步骤并将它们编写为异步函数(带回调参数)

  • 读取文件

    function readFile(readFileCallback) {
        fs.readFile('stocktest.json', function (error, file) {
            if (error) {
                readFileCallback(error);
            } else {
                readFileCallback(null, file);
            }
        });
    }
    
  • 处理文件(我在示例中删除了大部分 console.log)

    function processFile(file, processFileCallback) {
        var stocksJson = JSON.parse(file);
        if (stocksJson[ticker] != null) {
            stocksJson[ticker].price = value;
            fs.writeFile('stocktest.json', JSON.stringify(stocksJson, null, 4), function (error) {
                if (err) {
                    processFileCallback(error);
                } else {
                    console.log("File successfully written");
                    processFileCallback(null);
                }
            });
        }
        else {
            console.log(ticker + " doesn't exist on the json");
            processFileCallback(null); //callback should always be called once (and only one time)
        }
    }
    

请注意,我在这里没有进行具体的错误处理,我将利用 async.waterfall 将错误处理集中在同一个地方。

还要注意,如果您在异步函数中有 (if/else/switch/...) 分支,它总是会调用一次(且仅一次)回调。

使用 async.waterfall 插入所有内容

async.waterfall([
    readFile,
    processFile
], function (error) {
    if (error) {
        //handle readFile error or processFile error here
    }
});

干净的例子

前面的代码过于冗长以使解释更清楚。这是一个完整的清理示例:

async.waterfall([
    function readFile(readFileCallback) {
        fs.readFile('stocktest.json', readFileCallback);
    },
    function processFile(file, processFileCallback) {
        var stocksJson = JSON.parse(file);
        if (stocksJson[ticker] != null) {
            stocksJson[ticker].price = value;
            fs.writeFile('stocktest.json', JSON.stringify(stocksJson, null, 4), function (error) {
                if (!err) {
                    console.log("File successfully written");
                }
                processFileCallback(err);
            });
        }
        else {
            console.log(ticker + " doesn't exist on the json");
            processFileCallback(null);
        }
    }
], function (error) {
    if (error) {
        //handle readFile error or processFile error here
    }
});

我留下了函数名称,因为它有助于提高可读性并有助于使用 chrome 调试器等工具进行调试。

如果您使用 underscore ( on npm ),您也可以将第一个函数替换为 _.partial(fs.readFile, 'stocktest.json')

关于javascript - 在 node.js 中使用异步 waterfall ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25705067/

相关文章:

javascript - 如何以 js 格式呈现 index.js.erb? ( ruby 1.8.7)

javascript - jQuery:传递scrollTop值后隐藏元素

node.js - 一次读取子进程标准输出 100 个字节

node.js - 在 Koa 中设置多个 cookie header

java - 使用 Java 进行异步 http 调用的最轻量级方法是什么?

JavaScript RegExp 方法 exec() 只返回一项

javascript - 比较两个数组的元素

node.js - 用 Mongoose 查询和求和

asynchronous - 无法看到在julia @spawn方法内发生的错误

javascript - 所有异步操作完成后的回调