j6ndev
10/7/2019 - 10:59 PM

handling errors like golang

let readFile = require("./readFile");

async function main() {
  let [err, file] = await readFile("./test.js");

  if (err) {
    // handle `err`
  }

  // do something with `file`
}

main();


// readFile.js
let util = require("util");
let fs = require("fs");

let read = util.promisify(fs.readFile);

module.exports = async path => {
  try {
    let res = await read(path, { encoding: "utf8" });
    return [null, res];
  } catch (err) {
    return [err, null]
  }
};