【问题标题】:How to execute the java script code sequentially?如何按顺序执行javascript代码?
【发布时间】: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

【问题讨论】:

标签: javascript node.js asynchronous async-await


【解决方案1】:

await 仅对 Promise 有用。

但是fs.readFile 返回undefined,因此在其上使用它没有任何意义。

如果您使用 VSC,您可以将鼠标悬停在上面并看到它返回 void,这意味着什么都没有,这意味着 undefined

你可以做的是承诺readFilewriteFile。为此,您可以使用new Promise()

function write(date) {
  return new Promise((res, rej) => {
    fs.writeFile("lastrundetail.txt", date, function(err) {
      if (err) return rej(err);
      res("Step 5 : Saved the record in file");
    });
  });
}

这个函数会给你一个承诺。您可以使用res 解决或使用rej 拒绝

现在你可以看到它返回了一个承诺

错误时你拒绝,否则你解决承诺。

readFile 也一样

function read(filePath) {
  return new Promise((res, rej) => {
    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"
          );
          res(data);
        } else {
          rej(err);
        }
      }
    );
  });
}

在这里我解决了data。稍后当我们使用let data = await read(...) 时,它会返回我们的数据。 现在这两个函数都返回一个未决的承诺。

现在在我们的函数上使用await 是有意义的

async function checkPreviousRunDate() {
  console.log("Step 1 : Today's Date: " + todaysDate.getDate());
  filePath = path.join(__dirname, "lastrundetail.txt");
  let data = await read(filePath);
  console.log(data);
}

async function storeTodaysDateinLastRunFile() {
  console.log("Step 4 : Finally Saving the todays date in last run file: ");
  await write(todaysDate);
  return todaysDate;
}

如果发生错误,您可以将其包装在您通常应该做的try / catch 中。这将捕获rej 错误

async function checkPreviousRunDate() {
  console.log("Step 1 : Today's Date: " + todaysDate.getDate());

  filePath = path.join(__dirname, "lastrundetail.txt");
  try {
     let data = await read(filePath);
     console.log(data);
  catch (err) {
     console.log(err);
  }
}

【讨论】:

    猜你喜欢
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 2012-02-26
    • 1970-01-01
    • 2018-12-15
    • 2017-07-30
    相关资源
    最近更新 更多