Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions solutions/promises_async_await/5.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
const URL = "https://whatthecommit.com/index.json";

// using .then and .catch
const fetchUsingThen = () => {
const requests = [];
for (let i = 0; i < 10; i++) {
requests.push(fetch(URL));
}

Promise.all(requests)
.then((responses) => Promise.all(responses.map((result) => result.json())))
.then((data) => console.log(data))
.catch((err) => console.log("Error: " + err));
};

fetchUsingThen();

// fetch using async await
const fetchAsyncAwait = async () => {
const requests = [];
for (let i = 0; i < 10; i++) {
requests.push(fetch(URL));
}

try {
const responses = await Promise.all(requests);
const data = await Promise.all(responses.map((result) => result.json()));
console.log(data);
} catch (error) {
console.log("Error: " + error);
}
};

fetchAsyncAwait();

// simple fetch for 1 time
const getFetch = () => {
fetch(URL)
.then((res) => res.json())
.then((data) => console.log(data));
};

getFetch();
Comment on lines +36 to +43

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// simple fetch for 1 time
const getFetch = () => {
fetch(URL)
.then((res) => res.json())
.then((data) => console.log(data));
};
getFetch();