Different types of asynchronous functions

Viewed 26

How is an asynchronous function such as fs.readFile written such that it is asynchronous but different from a function decorated with the async keyword? Does an async function always return a promise?

The following works:

const Area = async (L, B) => L * B;

Area(5, 4).then(
  a => console.log("Area is " + a)
);

However, a function like fs.readFile after invocation will result in an undefined value.

When using a function from a third-party library, is there a way to tell that a function is asynchronous other than from its documentation?

1 Answers

fs.readFile implements asynchronousness through a callback, it returns nothing.

By contrast, fsPromises.readFile implements asynchronousness by returning a promise.

The callback flavor of asynchronousness can be converted into the promise flavor with the util.promisify function.

The async prefix must be applied to a function if the code in the function body makes use of the await keyword. A function with that prefix always returns a promise (like your Area), but promise-returning functions are possible without the async prefix, for example:

function timeout(ms) {
  return new Promise(function(resolve, reject) {
    setTimeout(resolve, ms);
  });
}

Whether a function is asynchronous, and if so whether it uses the callback or promise flavor should be documented. If that is not the case, you can only try out its behavior. Note that a function could have several callbacks, and perhaps also return a promise. There are more types of asynchronous behavior than just the one enabled by async.

Related