Async

This notebook introduces the support for working with async operations and async APIs in node.js.

In a typical notebook, one cell completes execution before the next begins. This ensures simple things such as console output from code in a cell is associated with the cell, rather than some other arbitrary cell that is executing. More importantly it ensures that variables defined within one cell are declared and initialized before the next cell executes, where these variables might be referenced.

Notebooks automatically reference the ijs.runtime node module which includes an async helper API that allows returning promises representing asynchronously returned results (or errors) when using async APIs such as making HTTP requests.

In this notebook, a much simpler example is used. A timeout set 3 seconds into the future. Once the timeout is reached, some text is emitted into the notebook, and a result is produced.

A Simple Example


In [1]:
_.async(function(deferred) {
  setTimeout(function() { 
    console.log("hello!"); 

    var result = 'done';
    deferred.resolve(result);
  }, 3000);
});


hello!
done

Deferred API

The async helper method takes a function as an argument that it will invoke and pass in a deferred object. It returns the promise represented by this deferred object, which the notebook will monitor for completion of the function.

This deferred object has two methods:

  • resolve(result): call this on successful completion of the async work.

  • reject(error): call this when there is an error.

A Realistic Example

Most node.js APIs use the callback pattern to enable code to resume with async results or errors. In the promises world, your callbacks invoke the resolve and reject methods.


In [2]:
var http = require('http');

_.async(function(deferred) {
  _.request('http://www.example.org', function(err, response) {
    if (err || (response.statusCode != 200)) {
      deferred.reject(err || new Error('Failed request'));
    }

    deferred.resolve('Successful request; status = ' + response.statusCode);
  })
});


Successful request; status = 200

In [ ]: