Asynchronous requests in JavaScript

fetch, promises (then, catch, finally), async and await, the execution order of asynchronous code and the handling of network and HTTP errors.

  • 26 cards
  • 4 topics
  • Free

The outline, topic by topic

Each topic is weighted the way the exam weighs it.

  1. Concepts
  2. Questions
  3. Sort and link
  4. Scenarios

A few cards from the deck

  • Event loop: what is it?

    Show the answer

    The mechanism that runs code on a single thread, then handles the pending tasks in turn: first all the microtasks, then the next task.

    A setTimeout(f, 0) does not run f right away: it queues it, and it waits for the current code to finish. Promise .then callbacks go before it.

  • In what order do the letters appear?

    ```javascript
    console.log('A');
    setTimeout(() => console.log('B'), 0);
    Promise.resolve().then(() => console.log('C'));
    console.log('D');
    `

    • A D C B
    • A B C D
    • A D B C
    • A C D B
    Show the answer

    A D C B

    Synchronous code goes first (A, D). Microtasks (the .then, C) go before tasks (the setTimeout, B), even with a 0 ms delay.

  • The server answers 404: the fetch promise is …, and it is the response's … property, false here, that flags the problem.

    Show the answer

    The server answers 404: the fetch promise is fulfilled, and it is the response's ok property, false here, that flags the problem.

    To handle an error code in the catch, write if (!response.ok) throw new Error(response.status): the HTTP error then becomes a rejected promise.

  • Promise: what is it?

    Show the answer

    An object representing a future result: it starts pending, then is fulfilled with a value or rejected with an error, and never changes after that.

    The three states are pending, fulfilled and rejected. The value is retrieved with .then, the error with .catch.

  • The server answers 404, yet the catch block around the fetch does not trigger: the code carries on and crashes later. What is the cause and the fix?

    • fetch only rejects on a network failure; test response.ok and throw an error
    • The catch must be replaced by a finally that receives the error code
    • The server should answer 500: a 404 is not an error
    • An await must be added before catch so it waits for the response
    Show the answer

    fetch only rejects on a network failure; test response.ok and throw an error

    For fetch, a 404 is a response received: the promise is fulfilled. Test if (!response.ok) throw new Error(response.status) so the HTTP error goes through the catch.