JSlang.dev

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

January 25, 2024
TestsSource
async+await

Source Code

The source code we wrote during the event.

import {strict as assert} from 'assert';

describe('What happens to errors inside async functions?', () => {
  it('an async function can also throw', async () => {
    async function f() {
      throw Error('thrown');
    }
    await assert.rejects(f);
  });
  it('an async function returns data when awaited for its result', async () => {
    async function f() {
      return 'from the async function';
    }
    assert.equal(await f(), 'from the async function');
  });
  it('unawaited async function returns a Promise', () => {
    async function f() {}
    assert.ok(f() instanceof Promise);
  });
  it('an async function does not run the line after it throws an error', async () => {
    let wasCalled = false;
    async function f() {
      throw Error();
      wasCalled = true;
    }
    try {
      await f();
    } catch {
      // ignore the error that was thrown
    }
    assert.equal(wasCalled, false);
  });
});

describe('Can we use an async function for building a "delay"?', () => {
  it('resolving a delayed async function', async () => {
    const start = Date.now();
    const executor = (resolve) => {
      setTimeout(() => resolve(Date.now()), 1000);
    };
    const p = new Promise(executor);
    const delayed = await p;
    assert.ok(delayed - start >= 1000);
    // want to copy+waste? ==> await new Promise((resolve) => setTimeout(resolve, 1000));
  });
});

describe('Can it block the code execution?', () => {
  it('two awaits following one another run sequentially', async () => {
    async function f() { 
      await new Promise((resolve) => setTimeout(resolve, 100));
    };
    const before = Date.now();
    await f();
    await f();
    const after = Date.now();
    assert.ok(after - before >= 200);
  });
  it('running two async functions in parallel takes less time than two calls', async () => {
    async function f() {
      await new Promise((resolve) => setTimeout(resolve, 100));
    };
    const before = Date.now();
    await Promise.allSettled([f(), f()]);
    const after = Date.now();
    assert.ok(after - before < 200);
  });
});