ES9에서 추가된 for await of는 비동기 처리 반복문이다.
const urls = [
"https://jsonplaceholder.typicode.com/users/1",
"https://jsonplaceholder.typicode.com/users/2",
"https://jsonplaceholder.typicode.com/users/3",
"https://jsonplaceholder.typicode.com/users/4",
];
//for await of
const getData = async () => {
try {
const [one, two, three, four] = await Promise.all(
urls.map(async (url) => {
const res = await fetch(url);
return res.json();
})
);
console.log("1", one);
console.log("2", two);
console.log("3", three);
console.log("4", four);
} catch (err) {
console.log(err);
}
};
getData();
기존에는 await을 지원하는 반복문이 없어 위와 같이 코드를 짰어야 했다.
const getDataLoop = async () => {
const arrOfPromise = urls.map((url) => fetch(url));
for await (let req of arrOfPromise) {
const data = await req.json();
console.log(data);
}
};
getDataLoop();
일반적인 for문에 await을 작성하면 for문 안에서도 await을 사용할 수 있다.
'Front-end > JavaScript' 카테고리의 다른 글
JS 비동기 6편 - allSettled, any (0) | 2023.04.18 |
---|---|
JS 비동기 5편 - parallel, race, sequencial (0) | 2023.04.13 |
JS 비동기 3편 - finally (0) | 2023.04.10 |
JS 비동기 2편 - async (0) | 2023.03.20 |
JS 비동기 1편 - Promise (0) | 2023.03.18 |