首先确定步骤并将它们编写为异步函数(采用回调参数)
-
读取文件
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 调试器等工具进行调试。
如果你使用下划线 http://underscorejs.org/ (on npm https://www.npmjs.org/package/underscore),您还可以将第一个函数替换为_.partial(fs.readFile, 'stocktest.json')