Async - sarahduv-401-advanced-javascript/seattle-javascript-401d32 GitHub Wiki

Async

FS

  • To use: require('fs')
  • All the methods have asynchronous and synchronous forms.
  • The asynchronous form always takes a completion callback as its last argument. The arguments passed to the completion callback depend on the method, but the first argument is always reserved for an exception. If the operation was completed successfully, then the first argument will be null or undefined.

Error first callbacks

  • If Google’s V8 Engine is the heart of your Node.js application, then callbacks are its veins. They enable a balanced, non-blocking flow of asynchronous control across modules and applications. But for callbacks to work at scale you’ll needed a common, reliable protocol. The “error-first” callback (also known as an “errorback”, “errback”, or “node-style callback”) was introduced to solve this problem, and has since become the standard for Node.js callbacks. fs.readFile('/foo.txt', function(err, data) { // If an error occurred, handle it (throw, propagate, etc) if(err) { console.log('Unknown Error'); return; } // Otherwise, log the file contents console.log(data); });

Async

  • The async function declaration defines an asynchronous function, which returns an AsyncFunction object. An asynchronous function is a function which operates asynchronously via the event loop, using an implicit Promise to return its result.