在Node.js的使用异步瀑布 [英] Using Async waterfall in node.js
问题描述
我有2个功能,我是异步运行的,我想他们使用waterfalll模式来写,事情是,我不知道如何..
这里是我的code:
I have 2 function that i'm running asynchronously, i'd like to write them using the waterfalll model, the thing is that i don't know how.. Here is my code :
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 the 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 /开关/ ...)的异步函数分支,它总是调用回调一个(只)的时间。
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
}
});
清洁例如
在previous code是过于冗长,使说明更清晰。这里是一个完整的清洗例如:
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
}
});
我离开了函数名,因为它有助于可读性和帮助调试,像铬调试工具。
I left the function names because it helps readability and helps debugging with tools like chrome debugger.
如果您使用下划线(上NPM ),也可以替换为第一个函数 _。部分(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屋!