Front/JavaScript
for await of
밍꿔
2020. 11. 12. 15:53
반응형
for await of 구문은 반복문 내부에서 실행되는 비동기 서비스들에 대한 순서를 보장해준다.
예를들어, 아래의 상황에서의 결과는
const names = ['a', 'b', 'c', 'd'];
names.forEach(async (name) => {
const result = await service.asyncTest(name);
console.log(result.json());
});
console.log('서비스 종료');
맨 마지막에 찍혀 있는 '서비스 종료' 라는 로그가 처음 찍히게 된다
모든 api 통신 완료
{"a":"end"}
{"b":"end"}
{"c":"end"}
{"d":"end"}
* forEach에서의 모든 비동기 작업에 대한 순서를 보장 하지 않는다.
때문에 for await of 문으로 아래와 같이 변경하면 해당 이슈는 해결 가능하다.
const names = ['a', 'b', 'c', 'd'];
for await (let name of names){
const result = await service.asyncTest(name);
console.log(result.json());
};
console.log('서비스 종료');
출력 결과는,
{"a":"end"}
{"b":"end"}
{"c":"end"}
{"d":"end"}
모든 api 통신 완료
반응형