240610 TIL

Jun Young Kim·2024년 6월 10일
0

TIL

목록 보기
36/62

비동기 promise.all, async, await

비동기 프로그래밍

비동기 프로그래밍은 코드의 실행이 중단되지 않고 다음 작업으로 넘어가면서 동시에 여러 작업을 처리할 수 있는 방식입니다. 이는 특히 I/O 작업(예: 파일 읽기/쓰기, 네트워크 요청 등)이 많을 때 유용합니다. JavaScript에서는 비동기 처리를 위해 콜백 함수, 프로미스(Promise), 그리고 async/await 문법을 사용합니다.

Promise

Promise는 비동기 작업의 완료 또는 실패를 나타내는 객체입니다. Promise는 세 가지 상태를 가질 수 있습니다:

  • 대기 중(Pending): 초기 상태, 비동기 작업이 아직 완료되지 않은 상태
  • 이행됨(Fulfilled): 비동기 작업이 성공적으로 완료된 상태
  • 거부됨(Rejected): 비동기 작업이 실패한 상태
let promise = new Promise(function(resolve, reject) {
    // 비동기 작업 수행
    if (성공) {
        resolve("성공 결과");
    } else {
        reject("실패 이유");
    }
});

promise.then(function(result) {
    console.log(result); // 성공 시 처리
}).catch(function(error) {
    console.error(error); // 실패 시 처리
});

Promise.all

Promise.all은 여러 개의 프로미스를 병렬로 처리할 수 있게 해줍니다. 모든 프로미스가 이행될 때까지 기다렸다가, 모든 결과를 배열로 반환합니다. 하나라도 거부되면 전체가 거부됩니다.

let promise1 = Promise.resolve(1);
let promise2 = Promise.resolve(2);
let promise3 = Promise.resolve(3);

Promise.all([promise1, promise2, promise3])
    .then(function(results) {
        console.log(results); // [1, 2, 3]
    })
    .catch(function(error) {
        console.error(error);
    });

async / await

async 함수는 항상 프로미스를 반환하며, await는 프로미스가 이행될 때까지 기다립니다. awaitasync 함수 안에서만 사용할 수 있습니다.

async 함수 선언

async function myFunction() {
    return "Hello";
}

myFunction().then(console.log); // "Hello"

await 사용

await는 프로미스가 해결될 때까지 함수 실행을 일시 정지합니다.

async function fetchData() {
    try {
        let response = await fetch('https://api.example.com/data');
        let data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('Error:', error);
    }
}

fetchData();

Promise.allasync/await 결합

Promise.allasync/await를 함께 사용하면, 여러 비동기 작업을 병렬로 처리하면서도 코드를 동기적으로 작성할 수 있습니다.

async function fetchAllData() {
    let urls = [
        'https://api.example.com/data1',
        'https://api.example.com/data2',
        'https://api.example.com/data3'
    ];

    try {
        let promises = urls.map(url => fetch(url).then(response => response.json()));
        let results = await Promise.all(promises);
        console.log(results);
    } catch (error) {
        console.error('Error:', error);
    }
}

fetchAllData();

요약

비동기 프로그래밍은 코드의 실행을 중단하지 않고 여러 작업을 동시에 처리하는 방식입니다.
Promise는 비동기 작업의 완료 또는 실패를 나타내는 객체입니다.
Promise.all은 여러 개의 프로미스를 병렬로 처리하고, 모든 프로미스가 이행될 때까지 기다립니다.
asyncawait은 비동기 코드를 더 간단하고 동기적으로 보이게 작성할 수 있게 해줍니다. async 함수는 프로미스를 반환하며, await는 프로미스가 이행될 때까지 기다립니다.

이러한 개념들을 이해하고 활용하면, JavaScript에서 비동기 작업을 더 효율적이고 깔끔하게 처리할 수 있습니다.

0개의 댓글