๐ด Async Await
// using then, catch
const getMoviesPromise = () => {
fetch("https://yts.am/api/v2/list_movies.json")
.then(response => {
console.log(response);
return response.json();
})
.then(json => console.log(json))
.catch(error => console.log(error));
};
// using async, await
const getMoviesAsync = async () => { // then => await
const response = await fetch("https://yts.am/api/v2/list_movies.json");
const json = await response.json();
console.log(json);
};
๐ try catch finally
const getMoviesAsync = async () => {
try {
const response = await fetch("https://yts.am/api/v2/list_movies.json")
const json = await response.json();
throw Error("I'm hungry");
} catch (e) {
console.log(error);
} finally {
console.log("We are done");
}
};
// Error: I'm hungry
// We are done!
๐ก Parallel Async Await
const getMoviesAsync = async () => {
try {
const [moviesResponse, suggestionsResponse] = await Promise.all([
fetch("https://yts.am/api/v2/list_movies.json"),
fetch("https://yts.am/api/v2/movie_suggestions.json?movie_id=100")
]);
const [movies, suggestions] = await Promise.all([
moviesResponse.json(),
suggestionsResponse.json()
]);
console.log(movies, suggestions);
} catch(e) {
console.log(error);
} finally {
console.log("We are done!");
}
};
'JavaScript' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ JS ] Symbol, Set and Map (0) | 2022.07.06 |
---|---|
[ JS ] Classes (0) | 2022.07.06 |
[ JS ] Promises (0) | 2022.07.06 |
[ JS ] For Loop (0) | 2022.07.05 |
[ JS ] Rest And Spread (0) | 2022.07.05 |