상세 컨텐츠

본문 제목

[Javascript] 비동기 처리(4) : Loop 와 Async/Await

😎 지식/FE-리액트🌐

by :Eundms 2021. 8. 18. 10:11

본문

Async(비동기) / Await(대기)

 

동기

//동기적으로 작업이 실행됨
for (var i=0;i<array.length;i++){
    var item=array[i];
}

array.forEach((item)=>{
});

비동기

// 비동기 - 구문 오류
// processArray는 비동기 함수이지만,
// forEach에 사용하는 익명함수는 동기식이다.

async function processArray(array){
    array.forEach(item=>{
        await func(item);
    })
}

 

// 방법1) - 익명함수도 비동기함수로 정의 -잘못된 방법
// 처음에 내가생각했던해결 방법,,,,
async function processArray(array){
    array.forEach(async(item)=>{
        await func(item);
    })
    console.log('Done!');
}

// 문제점 : Done! 1 2 3 가 실행됨 - 다음 예시 확인해보자
function delay() {
  return new Promise(resolve => setTimeout(resolve, 300));
}

async function delayedLog(item) {
  // notice that we can await a function
  // that returns a promise
  await delay();
  console.log(item);
}
async function processArray(array) {
  array.forEach(async (item) => {
    await delayedLog(item);
  })
  console.log('Done!');
}

processArray([1, 2, 3]);

 

// 방법2) - 배열을 순서대로 처리  1 2 3 Done!
async function processArray(array){
    for (const item of array){
        await delayedLog(item);
    }
    console.log('Done!);
}

 

// 방법3) 병렬 처리 배열
// 여기서 병렬은 스레드를 병렬 처리한다는 뜻이 아니다.

async function processArray(array){
    const promises=array.map(delayedLog);
    await Promise.all(promises);
    console.log('Done!');
}


현실적인 예시 ) 데이터베이스 쿼리는 네트워크 연결이 필요하므로 본질적으로 비동기식이다.

const userIds=[15,16,21]; 에 대해서 await getUserObject(userId);

const getUserObject =async(id)=>{

   

}

 


https://lavrton.com/javascript-loops-how-to-handle-async-await-6252dd3c795/

 

JavaScript loops - how to handle async/await

How to run async loops in sequence or in parallel? Before doing asynchronous magic with loops I want to remind you how we write classical…

lavrton.com

https://advancedweb.hu/asynchronous-array-functions-in-javascript/

 

관련글 더보기

댓글 영역