JavaScript Async Await and Fetch API
async and await let you write asynchronous code that reads like normal, top to bottom code. They work on top of promises.
- An
asyncfunction always returns a promise. await(inside an async function) waits for a promise and gives its result.
function wait(ms) {
return new Promise(resolve => setTimeout(() => resolve("Done after " + ms), ms));
}
async function run() {
console.log("Start");
const result = await wait(500);
console.log(result);
console.log("End");
}
run();
Output of the above program is
Start
Done after 500
End
Fetch API: get data from a server
fetch() sends a request and returns a promise. We use the free test API JSONPlaceholder.
async function getPost() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
const post = await response.json(); // read the JSON body
console.log(post.id);
console.log(post.userId);
console.log(post.title);
}
getPost();
Output of the above program is
1
1
sunt aut facere repellat provident occaecati excepturi optio reprehenderit
- The first
awaitwaits for the response headers. response.json()reads the body and turns the JSON into an object. It is also a promise.
Error handling
fetch() rejects only when the network fails. For a 404 or 500 answer the promise is still fulfilled, so check response.ok.
async function getPost(id) {
try {
const response = await fetch("https://jsonplaceholder.typicode.com/posts/" + id);
if (!response.ok) {
throw new Error("Server answered " + response.status);
}
return await response.json();
} catch (error) {
console.log("Failed: " + error.message);
}
}
getPost(99999);
Output of the above program is
Failed: Server answered 404
Send data with POST
async function createPost() {
const response = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: "Hello", body: "My post", userId: 1 })
});
const data = await response.json();
console.log(data.id);
}
createPost();
Output of the above program is
101
Note:
JSONPlaceholder pretends to save the data and returns id 101. Nothing is stored. See the same API used in PHP in PHP REST API.
Run tasks together
const [a, b] = await Promise.all([fetch(url1), fetch(url2)]);
Summary
asyncfunctions return promises, andawaitpauses until a promise is ready.- Use
fetch()to call APIs, andresponse.json()to read JSON. - Handle errors with
try...catchand checkresponse.ok. - Next: Local Storage.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |