繁体   English   中英

如何处理 Node.js 中的异步函数

[英]How to handle asynchronous functions in Node.js

I am using Node to pre-process .csv files into .json file for that I'm using the CSVTOJSON npm package.

我想等待解析完成,然后启动向数据库的上传过程。

我发现 Node 需要将函数与回调链接起来才能异步执行它们。

但我不知道如何申请我的计划。

这是代码

// 1. Read *.csv file + Parse fields and escape; @dir "raw_data" =>  @dir "processed"
fs.readdir(rawDataPath, function (err, files) {
  if (err) return console.log("Unable to scan raw_data : " + err);

  console.log("Processing csv files to JSON...");
  console.log("+++++++++++++++++++++++++++++++++++++++++++++++++++++++");

  files.forEach(function (file) {
    console.log(`CSV ${file.split(".")[0]} being converted...`);

    csv({ ignoreEmpty: true })
      .fromFile("raw_data/" + file)
      .then((jsonObj) => {
        // stringify JSON Object
        var jsonContent = JSON.stringify(jsonObj);

        fs.writeFile(
          `processed_data/${file.split(".")[0]}.json`,
          jsonContent,
          "utf8",
          function (err) {
            if (err) {
              console.log(
                "An error occured while writing JSON Object to File."
              );
              return console.log(err);
            }

            console.log(
              `${file} successfully converted to ${file.split(".")[0]}.json`
            );
          }
        );
      });
  });
});

// 2. Upload to Cloud Firestore
fs.readdir(processedDataPath, function (err, files) {
  if (err) return console.log("Unable to scan processed_data : " + err);

  files.forEach(function (file) {
    var quiz = require("./processed_data/" + file);

    console.log(`Collection ${file.split(".")[0]} being updated...`);

    quiz.forEach(function (obj) {
      firestore
        .collection(`${file.split(".")[0].toUpperCase()}`)
        .doc(obj.id)
        .set(obj)
        .then(function (docRef) {
          console.log(
            `Document ${obj.id} successfully uploaded to Cloud Firestore!`
          );
        })
        .catch(function (error) {
          console.error("Error adding document: ", error);
        });
    });
  });
});

有多种方法可以处理 Javascript 的异步特性。 我将使用fs.readFile()作为示例来简化它。 这些是一些方法 -

  1. 回调- 传递 function 作为要在异步任务完成后调用的参数。
fs.readFile('./some-file.txt', (err, res) => {
  if (err) {                   // err is null if success
    return console.log(err);   // handle error
  }
  console.log(res);            // handle success
});
  1. Promises - 这是 Javascript 中全局可用的 object 以延迟方式处理异步任务。 它还提供了链接多个 Promise 的能力。
fs.promises.readFile('./some-file.txt').then((res) => {
  console.log(res);            // handle success
}).catch((err) => {            // only gets executed if there is an error
  console.log(err);            // handle error
});

链接 -

fs.promises.readFile('./some-1.txt').then((res) => {
  return fs.promises.readFile('./some-2.txt');            
  // handle success - 1
}).then((res) => {
  return fs.promises.readFile('./some-3.txt');            
  // handle success - 2
}).then((res) => {            
  // handle success - 3
}).catch((err) => { 
  console.log(err);
  // handle error            
});
  1. Async/Await - 这是处理 Promise 的更简单方法,在 ES2017 中引入。 另外,请注意 Async/Await 仅适用于 promise 返回函数。
const main = async () => {
  try {
    const res = await fs.promises.readFile('./some-file.txt');
    console.log(res)
    // handle success
  } catch(err) {
    console.log(err);
    // handle error
  }
}

延伸阅读——

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM