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.
- Concepts
- Questions
- Sort and link
- 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 runfright away: it queues it, and it waits for the current code to finish. Promise.thencallbacks 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 BA B C DA D B CA C D B
Show the answer
A D C BSynchronous code goes first (
A,D). Microtasks (the.then,C) go before tasks (thesetTimeout,B), even with a 0 ms delay.The server answers 404: the
fetchpromise is …, and it is the response's … property, false here, that flags the problem.Show the answer
The server answers 404: the
fetchpromise is fulfilled, and it is the response's ok property, false here, that flags the problem.To handle an error code in the
catch, writeif (!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
catchblock around thefetchdoes not trigger: the code carries on and crashes later. What is the cause and the fix?fetchonly rejects on a network failure; testresponse.okand throw an error- The
catchmust be replaced by afinallythat receives the error code - The server should answer 500: a 404 is not an error
- An
awaitmust be added beforecatchso it waits for the response
Show the answer
fetchonly rejects on a network failure; testresponse.okand throw an errorFor
fetch, a 404 is a response received: the promise is fulfilled. Testif (!response.ok) throw new Error(response.status)so the HTTP error goes through thecatch.