gpt4 book ai didi

node.js - 尝试了解 Await/Async,这是正确的转换吗?

转载 作者:太空宇宙 更新时间:2023-11-03 21:52:56 25 4
gpt4 key购买 nike

所以我尝试使用 Node 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;
}

最佳答案

我会把它分成两个函数。它更容易阅读,并且 try/catch 更少。

我自己的规则是,当我看到嵌套的 try/catch 或嵌套的数组函数时,这意味着您必须创建单独的函数。

     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;
}

关于node.js - 尝试了解 Await/Async,这是正确的转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48670559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com