< Previous Article Next Article >

pjs.wrap()

The pjs.wrap() API accepts an asynchronous function that requires a callback and creates a new function that can be called without a callback. It helps you write business application code in a more intuitive top-down manner.

Simple usage

// Read a file
const fs = require('fs');
let readFile = pjs.wrap(fs.readFile);
let text = readFile("somefile.txt", 'utf8');

Passing this parameter

pjs.wrap() can optionally accept a 2nd parameter, indicating how the keyword this should be treated inside the function.

Typically, the parent object of the function is passed. This would only be required if internally the function uses the keyword this. For, example, to be safe, let's adjust the example above as follows:

// Read a file
const fs = require('fs');
let readFile = pjs.wrap(fs.readFile, fs);  // we pass fs in case the keyword this is used inside fs.readFile()
let text = readFile("somefile.txt", 'utf8');

Wrapping in mass

If you pass an object to pjs.wrap(), such as fs, it will convert all of its methods to be top-down, and attach the resulting methods into a property named fiber.

// Replace text in a file
const fs = pjs.wrap(require('fs'));
let text = fs.fiber.readFile("somefile.txt", 'utf8');
let newText = text.replace(/in progress/g, "completed");
fs.fiber.writeFile("somfile.txt", newText);

Handling errors

If an error occurs when calling a wrapped function, the error object is no longer passed to a callback. Instead, it will be thrown within the current function scope. You can let your program error out or use a try / catch construct if an error condition is exepcted.

const fs = require('fs');
let readFile = pjs.wrap(fs.readFile, fs);
try {
  var text = readFile("somefile.txt", 'utf8');
}
catch (err) {
  // Maybe the file doesn't exist?
}

Questions?

Have questions about this topic? Ask for help on our NodeRun Discussion Forum.

< Previous Article Next Article >