case – A
const BASE_URL = "https://bootcamp-api.codeit.kr/api";
export async function fetchData(endpoint) {
const response = await fetch(`${BASE_URL}/sample/${endpoint}`);
if (!response.ok) {
throw new Error("Fail");
}
return await response.json();
}
export async function getFolders() {
return await fetchData("folder");
}
export async function getUserProfile() {
return await fetchData("user");
}
case – B
export async function fetchData(endpoint) {
const response = await fetch(`${BASE_URL}/sample/${endpoint}`);
if (!response.ok) {
throw new Error("Fail");
}
return await response.json();
}
export function getFolders() {
return fetchData('folder');
}
export function getUserProfile() {
return fetchData('user');
}
What’s different in action ?
— Edited —
Why do we no need to add ‘async’ and ‘await’ keyword at case B ?
This code working same.
2
Answers
In the first case (getFolders or getUserProfile ), the await keyword ensures that the function waits for the fetchData promise to be resolved before proceeding.
in second case the function returns the unresolved promise immediately. If you want to work with the result of the fetchData operation, you need to use await or handle the promise using .then() in the calling code.
Using await allows you to work with the result of the asynchronous operation in a more synchronous style, making the code easier to read and understand.
An async function returns a promise. but if a promise returned from it there’s no need
async
since a promise returned anyway.For the same reason you should never do
return await
since you block the execution instead of returning immediately. Basically in that case you return a promise anyway but with the resolved value. The return value can be even discarded by the caller so it’s even a possible performance hit if youreturn await
.Never
return await
. The case B is right but should be fixed by removingreturn await
: