Answer the question
In order to leave comments, you need to log in
How to implement a function with many AJAX requests that returns their responses?
We need a JS function that will have many different AJAX-s and it should return their values so that they can then be accessed from other functions. How can I do that?
Answer the question
In order to leave comments, you need to log in
async...await, Promise.allSettled (very fresh, piping hot - can burn you).
async function getData() {
const urls = {
comments: 'https://jsonplaceholder.typicode.com/comments',
users: 'https://jsonplaceholder.typicode.com/users',
posts: 'https://jsonplaceholder.typicode.com/posts'
}
const data = {}
for (const [key, value] of Object.entries(urls)) {
const res = await fetch(value)
data[key] = await res.json()
}
return data
}
console.log(await getData())
let urls = [
'https://api.github.com/users/iliakan',
'https://api.github.com/users/remy',
'https://api.github.com/users/jeresig'
];
// map every url to the promise of the fetch
let requests = urls.map(url => fetch(url));
// Promise.all waits until all jobs are resolved
Promise.all(requests)
.then(responses => responses.forEach(
response => alert(`${response.url}: ${response.status}`)
));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question