Modules/Async/A

From CommonJS Spec Wiki
Jump to: navigation, search

STATUS: PROPOSAL

Implementations
[[Implementations/Yabble|]]

This a proposal for the specification of the "require.ensure" method. (Formerly "require.async".)

Contract

  1. An "ensure" function is defined as a property of the value of the free variable "require" provided in the module scope. "require.ensure" accepts an array of module identifiers as first argument and a callback function as second argument.
  2. The callback function must be called as soon as all of the foreign modules, and their shallow and deep dependencies are available for synchronous require.
    1. The callback function must be passed the "require" function as its first argument.

Unspecified

This specification leaves the following important points of interoperability unspecified:

  1. the return value of "require.ensure" to allow for future modifications of the specification, notably the inclusion of promises,
  2. the means by which the foreign modules are loaded, and
  3. the presence of a timeout.

Sample Code

math.js
exports.add = function() {
    var sum = 0, i = 0, args = arguments, l = args.length;
    while (i < l) {
        sum += args[i++];
    }
    return sum;
};
increment.js
var add = require('math').add;
exports.inc = function(val) {
    return add(val, 1);
};
program.js
require.ensure(['increment'], function(require) {
    var inc = require('increment').inc;
    var a = 1;
    inc(a); // 2
});


Notes

  • Given the semantic shift this method has taken thanks to Wes Garland's suggestions, the name "require.async" no longer seemed appropriate. We ended up agreeing on "require.ensure" instead.
  • This specification only defines "require.ensure" on the module scope's free variable "require". If a module loader also has a global variable "require", it MAY choose to mirror the ensure function on that object or function as well, but that is the module loader's prerogative.

Related Discussion