How to do it…

Let's start by seeing how a common error first callback works. The fs (file system) module provides a readFile() method that can read a file, and either produce its text or an error. My showFileLength1() function attempts to read a file, and list its length. As usual with callbacks, we have to provide a function, which will receive two values: a possible error, and a possible result.

This function must check whether the first argument is null or not. If it isn't null, it means there was a problem, and the operation wasn't successful. On the other hand, if the first argument is null, then the second argument has the file read operation result. The following code highlights the usual programming pattern used with Node callbacks; the lines in bold are the key ones:

// Source file: src/promisify.js

/* @flow */
"use strict";

const fs = require("fs");

const FILE_TO_READ = "/home/fkereki/MODERNJS/chapter03/src/promisify.js"; // its own source!

function showFileLength1(fileName: string): void {
fs.readFile(fileName, "utf8", (err, text) => {
if (err) {
throw err;
} else {
console.log(`1. Reading, old style: ${text.length} bytes`);
}
});
}
showFileLength1(FILE_TO_READ);

// continues...

This style of coding is well-known, but doesn't really fit modern development, based on promises and, even better, async/await. So, since version 8 of Node, there has been a way to automatically transform an error-first callback function into a promise: util.promisify(). If you apply that method to any old-style function, it will turn into a promise, which you can then work in simpler ways.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.96