【发布时间】:2021-03-16 07:09:11
【问题描述】:
我每天都在学习 javascript(nodejs) 中的新东西,但是让我很困惑的一件事是异步等待的概念。
在管理以下代码中的执行顺序时需要一点帮助。这是它应该如何执行的 我正在编写一个每日脚本,它应该从本地系统读取文件值(文件包含:上次运行日期)。 完成读取文件后在文件中添加一个新值(文件应存储当前日期)。
fs = require('fs');
path = require('path');
let todaysDate = new Date();
async function checkPreviousRunDate() {
console.log("Step 1 : Today's Date: " + todaysDate.getDate());
filePath = path.join(__dirname, 'lastrundetail.txt');
var filedata;
await fs.readFile(filePath, {
encoding: 'utf-8'
}, function(err, data) {
if (!err) {
console.log('Step 2 :Last run was done on(MM/DD/YYYY): ' + data);
let lastrunDate = new Date(data);
const diffTime = Math.abs(todaysDate - lastrunDate);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
console.log("Step 3 :Its been " + diffDays + " day(s) Since the last run");
return data;
} else {
console.log(err);
return "";
}
});
}
async function storeTodaysDateinLastRunFile() {
console.log("Step 4 : Finally Saving the todays date in last run file: ");
await fs.writeFile("lastrundetail.txt", todaysDate, function(err) {
if (err) return console.log(err);
console.log('Step 5 : Saved the record in file');
});
return todaysDate;
}
const main = async () => {
let lastrunDate = await checkPreviousRunDate();
let storedDate = await storeTodaysDateinLastRunFile();
}
main();
输出:
Step 1 : Today's Date: 4
Step 4 : Finally Saving the todays date in last run file:
Step 5 : Saved the record in file
Step 2 :Last run was done on(MM/DD/YYYY): Fri Dec 04 2020 13:10:01 GMT+0530 (India Standard Time)
Step 3 :Its been 1 day(s) Since the last run
预期输出:
Step 1 : Today's Date: 4
Step 2 :Last run was done on(MM/DD/YYYY): Fri Dec 04 2020 13:06:26 GMT+0530 (India Standard Time)
Step 3 :Its been 1 day(s) Since the last run
Step 4 : Finally Saving the todays date in last run file:
Step 5 : Saved the record in file
【问题讨论】:
-
fs.readFile不返回 Promise,因此,您不能await它 -fs.writeFile也是如此 -
您可能应该使用the promise API for FS 而不是回调函数。
await fs.readFile并没有真正等待整个文件读取完成。
标签: javascript node.js asynchronous async-await