试图理解Await / Async,这是正确的转换吗?

时间:2018-02-07 18:05:36

标签: node.js async-await

所以我试图使用节点8.9.4中的async / await模式重写以下回调函数。我是否正确或是否应该进一步改写?

const fs = require("fs");

const makeBackup = (file, callback) => {
    if(fs.existsSync(`${file}.bak`)) return callback(null, true);
    fs.copyFile(file, `${file}.bak`, cpErr => {
        if(cpErr && cpErr.code === "ENOENT"){
            fs.writeFile(`${file}.bak`, Buffer.alloc(0), writeErr => {
                if(writeErr) return callback(writeErr);
                return callback(null, true);
            });
        } else if(cpErr) return callback(cpErr);
        return callback(null, true);
    })
}

这是我提出的async / await函数。

import fs, { copyFile, writeFile } from "fs";
import { promisify } from "util";

const makeBackup = async file => {
  // if backup file exists already do nothing further return true.
  if (fs.existsSync(`${file}.bak`)) return true;
  try {
    copyFile = promisify(fs.copyFile);
    // if backup file doens't exist copy file to file.bak
    await copyFile(file, `${file}.bak`);
    // return true when file is copied to bakup file.
    return true;
  } catch (cpErr) {
    // if file missing create an empty backup file
    if (cpErr.code === "ENOENT") {
      try {
        writeFile = promisify(fs.writeFile);
        await writeFile(`${file}.bak`, Buffer.alloc(0));
        return true;
      } catch (writeErr) {
        // if error writing to file for any reason return error
        return writeErr;
      }
    }
    // if copy error for any other reason return error
    return cpErr;
  }

1 个答案:

答案 0 :(得分:2)

我会把它分成两个函数。它更容易阅读,并且尝试/捕获的次数更少。

我自己的规则是当我看到嵌套的try / catch或嵌套的Array函数时,这意味着你必须创建分离的函数。

     async makeBackup(file) {
        // if backup file exists already do nothing further return true.
        if (fs.existsSync(`${file}.bak`)) return true;

        try {
          copyFile = promisify(fs.copyFile);

          // if backup file doens't exist copy file to file.bak
          await copyFile(file, `${file}.bak`);

          // return true when file is copied to bakup file.
          return true;
        } catch (cpErr) {
          // if file missing create an empty backup file
          if (cpErr && cpErr.code === "ENOENT") {
            return createEmptyBackupFile(file);
          }

          // if copy error for any other reason return error
          return cpErr;
        }
     }

     async createEmptyBackupFile(file) {
        writeFile = promisify(fs.writeFile);

        // if error writing to file for any reason it will throw an error
        await writeFile(`${file}.bak`, Buffer.alloc(0));

        return true;
     }