for loop in async/await javascript pattern
/*
for 문 안에 있는 Async 함수를 Sync 하는 패턴으로
은근히 자주 쓰이는데 막상 쓰려면 찾기도 만들기도 어려운 개똥같은 패턴이라고 할 수 있다.
아래 시나리오는,
for 문을 돌면서 비동기 함수인 pushAsync 를 호출해서
datas 에 6,7,8,9,10 을 추가하려는 상황이다.
*/
console.log("=== START !");
datas = [1, 2, 3, 4, 5];
setTimeout (() => {
//의외로 [1, 2, 3, 4, 5] 가 나오지 않는다.
console.log("===== Amazing : " + datas);
}, 3000);
printAll();
/*
아래에서 번외로, printAll 에서 async 와 await 를 삭제하면 재미있는 일이 일어난다.
pushAsync 5개를 한꺼번에 실행하고 setTimeout 이 한꺼번에 등록되면서,
1초가 지난 후 연속적으로 5개가 실행 된다.
*/
async function printAll() {
for(var i = 0; i < 5; i++ ) { // for 안에서 비동기 함수가 동작할 것이다.
await pushAsync(i); //promise 를 리턴해야 await 로 사용 가능 하다.
}
console.log("=== END ? : " + datas);
}
function pushAsync(i) {
return new Promise((resolve) => {
setTimeout(() => {
console.log("Add " + (6 + i) + " to Array.");
datas.push(6 + i);
resolve(datas);
}, 1000);
});
}
// 비동기 프로그래밍을 많이 해왔다면
// 아래의 결과는 놀랍지 않을 것이다.
console.log("=== Not amazing : " + datas);
결과
=== START ! ===
Not amazing : 1,2,3,4,5
Add 6 to Array.
Add 7 to Array.
===== Amazing : 1,2,3,4,5,6,7
Add 8 to Array.
Add 9 to Array.
Add 10 to Array.
=== END ? : 1,2,3,4,5,6,7,8,9,10
0 개의 댓글:
댓글 쓰기