/ JavaScript

From Callbacks to Functional

As previously mentioned, the converter from the asynchronous functions returning the result via callback can be created to support the simple asynchronous programming with node.js[1].

As the first step, the read method can be slightly modified to better separate implementation from wrapper:

const read = filepath =>  
  callback => {
    const impl = (filepath, callback) => {
      const options = { encoding : 'utf8' };
      fs.readFile(filepath, options, callback);
    };
    return ('function' === typeof filepath)
      ? filepath((err, filepath) =>
        err != null ? callback(err) : impl(filepath, callback))
      : impl(filepath, callback);
  };

Let's define fn1 function that gets implementation with value and callback and returns the wrapped function:

const fn = f => arg1 => callback => ('function' === typeof arg1)
  ? arg1((err, arg1) => err != null ? callback(err) : f(arg1, callback))
  : f(arg1, callback);

The read function can be replaced then by wrapping the implementation with fn:

const read = fn1((filepath, callback) => {
  const options = { encoding : 'utf8' };
  fs.readFile(filepath, options, callback);
});

Similarly, other functions of the fs module can be converted:

var exists = fn1(fs.exists);
var mkdir = fn1(fs.mkdir);
...

Now it is possible to use these async functions in a simple way:

// write the string 'test' to the file 'folder-to-create'
// and then read this file and create the folder 'test',
// print result to console.
write('folder-to-create', 'test')(() =>
  mkdir(read('folder-to-create'))(console.log));

  1. Error Handling in 'read' and 'write', https://alexatnet.com/functional-error-handling/ ↩︎

Alex Netkachov

Alex Netkachov

Alex works at Central London on the next generation of energy trading solutions to traders, brokers and exchanges worldwide.

Read More

Why not to stay updated if the subject is interesting? Join Telegram channel Alex@Net or follow alex_at_net on Twitter. Or just, use the comments form below.