Files
javascript-examples/Writerside/topics/Promise.md
2024-06-21 14:34:12 +09:00

2.3 KiB

프로미스

let task1 = new Promise((resolve, reject) => {
    try {
        setTimeout(() => {
            resolve({ message: "OK" });
        }, 3000);
    } catch (e) {
        reject(e);
    }
});

let i = 0;
const uid = setInterval(() => {
    console.log(i);
    i++;
}, 500);

task1.then((result) => {
    console.log(result);
}).catch((reason) => {
    console.error(reason);
}).finally(() => {
    console.log("The End");
    clearInterval(uid);
});

프로미스를 생성할 때에는 2 개의 콜백을 사용합니다. resolve는 작업이 성공했을 때 결과를 반환하고, reject는 작업이 실패했을 때 호출합니다.

비동기 작업이 성공하면 then이 호출되고 resolve에서 전달한 값을 받습니다. 실패한 경우에는 catch가 호출되고 reject에서 전달한 값을 받습니다. finally는 성공 또는 실패한 경우에 호출됩니다.

  • Promise.resolve(val)
  • Promise.reject(val)
let task1 = Promise.resolve(100);

task1.then((result) => {
    console.log(result);
});

let task2 = Promise.reject("BAD");
task2.catch((reason) => {
    console.error(reason);
});
  • Promise.all()

    모든 프로미스가 완료된 이후에 결과가 배열로 전달됩니다.

  • Promise.race()

    처음으로 완료된 프로미스의 결과만 전달됩니다.

let task1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(3);
    }, 3000);
});
let task2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(2);
    }, 2000);
});
let task3 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(1);
    }, 1000);
});

Promise.all([task1, task2, task3])
    .then((result) => {
        console.log(result); // [3, 2, 1]
    });
Promise.race([task1, task2, task3])
    .then((result) => {
        console.log(result); // 1
    });

async / await

async function myFunction(param) {
    ...
}

async 함수를 정의하기 위해 사용됩니다. async 함수에는 await식이 포함될 수 있습니다. await 문은 async 함수의 실행을 일시 중지하고 전달 된 Promise의 해결을 기다린 다음 async 함수의 실행을 다시 시작하고 완료후 값을 반환합니다. await 키워드는 async 함수에서만 유효하다는 것을 기억하십시오.