在 node.js 中使用异步瀑布 [英] Using Async waterfall in node.js
问题描述
我有 2 个异步运行的函数.我想使用瀑布模型编写它们.问题是,我不知道如何..
I have 2 functions that I'm running asynchronously. I'd like to write them using waterfall model. The thing is, I don't know how..
这是我的代码:
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
知道如何使用瀑布编写它,以便我能够控制它吗?请给我写一些例子,因为我是 node.js 的新手
Any idea how can I write it using waterfall, so i'll be able to control this? Please write me some examples because I'm new to node.js
推荐答案
先确定步骤,写成异步函数(带回调参数)
读取文件
First identify the steps and write them as asynchronous functions (taking a callback argument)
read the file
function readFile(readFileCallback) { fs.readFile('stocktest.json', function (error, file) { if (error) { readFileCallback(error); } else { readFileCallback(null, file); } }); }
处理文件(我删除了示例中的大部分 console.log)
process the file (I removed most of the console.log in the examples)
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 将错误处理集中在同一个地方.
Note that I did no specific error handling here, I'll take benefit of async.waterfall to centralize error handling at the same place.
还要注意,如果您在异步函数中有 (if/else/switch/...) 分支,它总是会调用回调一次(并且只调用一次).
Also be careful that if you have (if/else/switch/...) branches in an asynchronous function, it always call the callback one (and only one) time.
async.waterfall([ readFile, processFile ], function (error) { if (error) { //handle readFile error or processFile error here } });
干净的例子
之前的代码过于冗长,使解释更清晰.这是一个完整的清理示例:
Clean example
The previous code was excessively verbose to make the explanations clearer. Here is a full cleaned example:
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 调试器等工具进行调试.
I left the function names because it helps readability and helps debugging with tools like chrome debugger.
如果你使用 underscore (在 npm),你也可以用
_.partial(fs.readFile, 'stocktest.json')
If you use underscore (on npm), you can also replace the first function with
_.partial(fs.readFile, 'stocktest.json')
这篇关于在 node.js 中使用异步瀑布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!