Better API for module.prefetch(id).

This commit is contained in:
Ben Newman
2017-04-25 10:24:36 -04:00
parent 5477aeac3f
commit d9264e3b4b
2 changed files with 26 additions and 8 deletions

View File

@@ -31,8 +31,10 @@ Mp.dynamicImport = function (id) {
// Returns a Promise that resolves to an Error object if importing the
// given id failed, and null otherwise.
Mp.prefetch = function (id) {
var module = this;
// Require the parent module from the complete meta graph.
var meta = requireMeta(this.id);
var meta = requireMeta(module.id);
var versions = Object.create(null);
var dynamicVersions = require("./dynamic-versions.js");
@@ -53,9 +55,12 @@ Mp.prefetch = function (id) {
var error = meta.errors && meta.errors[id];
if (error) {
// If there was an error resolving the top-level id, let that error be
// the final result of the module.prefetch(id) promise.
return Promise.resolve(error);
// If module.prefetch(id) fails, the failure will probably be reported
// as an uncaught promise rejection, unless the calling code
// deliberately handles the rejection. This seems appropriate because
// failed prefetches should not be fatal to the application, yet they
// should be noticeable, so that they can be cleaned up at some point.
return Promise.reject(error);
}
return cache.checkMany(versions).then(function (sources) {
@@ -76,6 +81,12 @@ Mp.prefetch = function (id) {
}
return missingTree && fetchMissing(missingTree);
}).then(function () {
// If everything was successful, the final result of the
// module.prefetch(id) promise will be the fully-resolved absolute
// form of the given identifier.
return module.resolve(id);
});
};

View File

@@ -153,13 +153,20 @@ describe("dynamic import(...)", function () {
import { shared } from "./imports/prefetch-child";
assert.deepEqual(shared, {});
const error = await module.prefetch("./imports/nonexistent.js");
assert.ok(error instanceof Error);
assert.ok(error.message.startsWith("Cannot find module"));
const rejection = module.prefetch("./imports/nonexistent.js");
let threw = false;
try {
await rejection;
} catch (e) {
assert.ok(e instanceof Error);
assert.ok(e.message.startsWith("Cannot find module"));
threw = true;
}
assert.strictEqual(threw, true);
assert.strictEqual(
await module.prefetch("./tests"),
null // Indicates no error.
"/tests.js"
);
return module.prefetch("./imports/prefetch").then(() => {