was following this tutorial(https://javascript.info/fetch) on javascript's promise and async await and had trouble understanding the exercise it provided.
The question is about retrieving multiple users info from Github. One fetch request per user. And requests shouldn’t wait for each other. So that the data arrives as soon as possible.
The solution it provided is
async function getUsers(names) {
let jobs = [];
for(let name of names) {
let job = fetch(`https://api.github.com/users/${name}`).then(
successResponse => {
if (successResponse.status != 200) {
return null;
} else {
return successResponse.json();
}
},
failResponse => {
return null;
}
);
jobs.push(job);
}
let results = await Promise.all(jobs);
return results;
}
My first question is, can we use await
for the fetch. i.e. is the following snippet equivalent to the solution he provided?
async function getUsers2(names) {
let jobs = [];
for(let name of names) {
let response
try {
response = await fetch(`https://api.github.com/users/${name}`);
} catch(e) {
response = null
}
const job = response && response.json()
jobs.push(job);
}
let results = await Promise.all(jobs);
return results;
}
Furthermore, the tutorial said
.then call is attached directly to fetch, so that when we have the response, it doesn’t wait for other fetches, but starts to read .json() immediately.
If we used await Promise.all(names.map(name => fetch(...))), and call .json() on the results, then it would wait for all fetches to respond. By adding .json() directly to each fetch, we ensure that individual fetches start reading data as JSON without waiting for each other.
Does he mean that if we write the solution this way
async function getUser(name) {
const response = await fetch(`https://api.github.com/users/${name}`)
return response.ok ? await response.json : null
}
async function getUsers(names) {
return await Promise.all(names.map(name => getUser(name)))
}
we wouldn't be able to achieve the effect such that we don't want requests shouldn’t wait for each other?