The JavaScript fetch()
method is promise-based, and can be used with async/await
. You can do so by creating an async
function, in which you need to do the following:
- Use
await
before thefetch()
call to wait for the promise to resolve and receive aResponse
object; - Read the
Response
stream to completion to extract the returned data in its intended form; - Use
try/catch
to handle any errors that might occur during the fetch operation.
The following code shows fetch()
method being used with promises:
fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => response.json()) .then(jsonData => { console.log(jsonData); }) .catch(err => { // ... });
This can be re-written in async/await
syntax in the following way:
(async function () { try { const response = await fetch('https://jsonplaceholder.typicode.com/todos/1'); const jsonData = await response.json(); console.log(jsonData); } catch (err) { // ... } })();
You can compare the two, to see how they differ syntactically.
Please note that starting with ES13/ES2022, in top-level modules, you no longer need to wrap await
in an async
function.
In the examples, the Response.json()
method is used to read the response stream to completion to extract the actual JSON data. The method is async
and must, therefore, be awaited in the async/await
syntax.
If your API returns different type of data than JSON, then you can either read the response stream using one of the built-in methods, or read the incoming stream in chunks.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.