Promises make it easy to express a asynchronous dependency tree - combined with await
/async
, we can effectively write an AMD-style require()
and define()
in only a few lines of code. In this demo, main.js loads a.js, which in turn requires b.js. With async functions, the first module will naturally pause for its dependency to resolve before it continues loaded, a nice CommonJS-like behavior that doesn't require pausing the event loop.
One caution is that if a module requires many other modules, it's a bad idea to await
them all in sequence, since each dependency would have to wait for the previous dependency to load and execute before it begins loading itself. Instead, use Promise.all()
to wrap up the dependencies, and then destructuring to unpack them:
define(async function() {
//these requests fire simultaneously
var [a, b, c] = await Promise.all([ require("a"), require("b"), require("c") ]);
//this code won't run until all have resolved in any order
console.log(a, b, c);
});