Search⌘ K
AI Features

The Callback Pattern: Synchronous vs. Asynchronous (II)

Explore the callback patterns in Node.js by understanding the differences between synchronous and asynchronous approaches. Learn when to use direct style synchronous APIs and how to guarantee asynchronicity with process.nextTick or setImmediate. This lesson helps you handle callback design effectively, avoiding common pitfalls like blocking the event loop or inconsistent callback invocation.

Using synchronous APIs

The lesson to learn from the unleashing Zalgo example is that it is imperative for an API to clearly define its nature: either synchronous or asynchronous.

One possible fix for our inconsistentRead() function is to make it completely synchronous. This is possible because Node.js provides a set of synchronous direct style APIs for most basic I/O operations. For example, we can use the fs.readFileSync() function in place of its asynchronous counterpart. The code would become as follows:

Node.js
import { readFileSync } from 'fs'
const cache = new Map()
function consistentReadSync (filename) {
if (cache.has(filename)) {
return cache.get(filename)
} else {
const data = readFileSync(filename, 'utf8')
cache.set(filename, data)
return data
} }
console.log(consistentReadSync("data.txt"))
// the next call will read from the cache
console.log(consistentReadSync("data.txt"))
...