Fibers
This page applies to Profound.js version 5 only. Fibers are unsupported in version 6 and newer. For Profound.js version 6 and newer, refer to the Promises documentation page.
Overview
Traditional JavaScript and Node.js APIs use the concept of asynchronous callbacks for virtually every input/output operation. It is a common pattern for Node.js APIs. Whether it is reading a disk file, accessing a database table, or calling a web service, the results are not returned directly to the caller; instead, they are passed into a separate function referred to as a callback.
Because of JavaScript’s design, the default way to “freeze” a computation and have the “rest of it” execute later (asynchronously) is to put “the rest of it” inside of a callback function.
The Callback Hell Problem
For certain types of applications, callbacks can be quite useful and performant; however, they also create the problem more commonly known as Callback Hell. A lot of code ends up looking like this:
fs.readdir(source, function (err, files) {
files.forEach(function (filename, fileIndex) {
gm(source + filename).size(function (err, values) {
aspect = (values.width / values.height);
widths.forEach(function (width, widthIndex) {
height = Math.round(width / aspect);
this.resize(width, height).write(dest + 'w' + width + '_' + filename, function(err) {
if (err) console.log('Error writing file: ' + err)
})
})
})
})
})Even when just a few simple APIs are being invoked, the pyramid shape and all the }) at the end are needed, because each API call returns its data into a separate anonymous callback function.
This is generally not conducive to writing top-down transactional business applications, where everything happens in a procedural manner, one step at a time. Instead of this:
fs.readdir(source, function (err, files) {
// process files here
});The business developer prefers this:
files = fs.readdir(source);
// process files hereCoding business applications in a top-down manner is more intuitive, especially if you come from a business application development background and have used languages such as RPG, CL, COBOL, and Java.
How Fibers Solve the Problem
To combat this problem and help eliminate Callback Hell, Profound.js integrates a component called Fibers. Through Profound.js Fibers, you can code input/output operations in a familiar top-down manner. All Profound.js input/output APIs use Fibers internally. You can also call any traditional asynchronous Node.js API in a top-down manner through the simple to use pjs.fiber.wrap() and pjs.fiber.run() APIs.
With Fibers, even though you code your applications in a simple top-down manner, asynchronous calls still happen behind the scenes. This ensures that your Node.js applications continue to perform and scale well. The Node.js event loop is not blocked when Fibers is used.