首先确定步骤并将其编写为异步函数(带有回调参数)
读取文件
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调试器之类的工具进行调试。
如果您使用下划线(在npm上),则还可以将第一个函数替换为
_.partial(fs.readFile,'stocktest.json')



