JSlang.dev

JavaScript Deep Dives with Wolfram. Since 2015
Inclusive, Test-Driven, Spec-Focused, Collaborative.

December 17, 2020
TestsSource
Top Level Await

Source Code

The source code we wrote during the event.

await new Promise((resolve) => {
  setTimeout(resolve, 10);
});

export default 'fast-file';
import {strict as assert} from 'assert';

const fastestFile = await Promise.any([
  import('./slow.js'),
  import('./not-existing.js'),
  import('./fast.js'),
]);

it('fastest import in a top level await wins', () => {
  assert.equal(fastestFile.default, 'fast-file');
});

xit('a stringified dynamic import starts with [Module]', async () => {
  const fastFile = await import('./fast.js');
  assert.equal(fastFile, '[Module] ...');
});
import {strict as assert} from 'assert';

try {
  await Promise.reject();
  it('a top level that throws can be caught, we should never see this', () => {
    assert(false);
  });
} catch {
  it('a top level that throws can be caught', () => {
    assert(true);
  });
}
import assert from 'assert';

const x = await 1;

describe('Top level await - How to test it?', () => {
  it('an await on the top level (see above) had been working', () => {
    assert.equal(x, 1);
  });
  it('an await inside eval throws, because ... (maybe we find out on twitter, #jslang)', () => {
    assert.throws(() => { eval('await 1') }, SyntaxError);
  });
});

const before = new Date().getTime();
const after = await new Promise((resolve) => {
  setTimeout(() => resolve(new Date().getTime()), 3000);
});
it('top level await blocks the execution until it resolves', () => {
  assert(before + 2000 < after);
});
await new Promise((resolve) => {
  setTimeout(resolve, 1000);
});

export default 'slow-file';