node/test/es-module/test-require-module-retry-import-errored.js
Joyee Cheung 7cb3a662da
module: allow ESM that failed to be required to be re-imported
When a ESM module cannot be loaded by require due to the presence
of TLA, its module status would be stopped at kInstantiated. In
this case, when it's imported again, we should allow it to be
evaluated asynchronously, as it's also a common pattern for users
to retry with dynamic import when require fails.

PR-URL: https://github.com/nodejs/node/pull/55502
Fixes: https://github.com/nodejs/node/issues/55500
Refs: https://github.com/nodejs/node/issues/52697
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Chemi Atlow <chemi@atlow.co.il>
2024-10-28 12:21:22 +00:00

36 lines
1.2 KiB
JavaScript

// This tests that after failing to require an ESM that contains TLA,
// retrying with import() still works, and produces consistent results.
'use strict';
const common = require('../common');
const assert = require('assert');
const { exportedReject } = require('../fixtures/es-modules/tla/export-promise.mjs');
assert.throws(() => {
require('../fixtures/es-modules/tla/await-export-promise.mjs');
}, {
code: 'ERR_REQUIRE_ASYNC_MODULE'
});
const interval = setInterval(() => {}, 1000); // Keep the test running, because await alone doesn't.
const err = new Error('rejected');
const p1 = import('../fixtures/es-modules/tla/await-export-promise.mjs')
.then(common.mustNotCall(), common.mustCall((e) => {
assert.strictEqual(e, err);
}));
const p2 = import('../fixtures/es-modules/tla/await-export-promise.mjs')
.then(common.mustNotCall(), common.mustCall((e) => {
assert.strictEqual(e, err);
}));
const p3 = import('../fixtures/es-modules/tla/await-export-promise.mjs')
.then(common.mustNotCall(), common.mustCall((e) => {
assert.strictEqual(e, err);
}));
exportedReject(err);
Promise.all([p1, p2, p3]).then(common.mustCall(() => { clearInterval(interval); }));