Promise는 비동기적으로 실행되는 작업의 성공과 실패 값을 나타내는 객체 입니다.
(Promise 안에 작업이 비동기일 수도 있고, 동기 일 수도 있다. 무조건 비동기 함수만 사용되는 것은 아니지만, Promise를 사용하여 비동기 작업 처리 결과를 좀 더 직관적(?) 으로 볼 수 있다.)
Promise는 3가지 상태 중 하나의 상태를 가지게 됩니다.
Promise객체는 new 키워드 생성자를 사용해 만듭니다.
비동기 작업 처리를 할 수 있는 콜백 함수를 인자(매개변수)로 받는데 총 2가지 1. resovle() 2. reject()
입니다.
resolve()
함수는 작업이 성공했을 때, reject()
함수는 작업이 실패했을 때 발생됩니다. 콜백 함수 데이터를 then(), catch()
메서드를 통해 받아 올 수 있습니다.
new Promise((resolve, reject) => {
if(true){
resolve('성공');
}else{
reject('실패');
}
});
✔ Promise는 콜백 함수를 호출 하지 않으면 계속 pending
(대기) 상태입니다.
new Promise(resolve => resolve)
// console.log 결과
Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "pending"
[[PromiseValue]]: undefined
✔ Promise 콜백 함수를 호출하여 값을 받을 수 있습니다.
new Promise(resolve => resolve('hello'));
// console.log 결과
Promise {<resolved>: "hello"}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: "hello"
Promise 처리가 완료된 데이터값은 methods을 통해 받아 올 수 있습니다. 대표적으로 then(), catch(), all(), resolve()
...등등 있습니다. 먼저 then()
에 대해서 알아보겠습니다.
then()
메서드는 Promise
를 리턴하고 두 개의 콜백함수를 매개변수로 받습니다.
1. Promise가 이행했을때, 2. Promise가 실패햇을 때를 위한 콜백함수 입니다.
promise.then(onFulfilled, onRejected);
// resolve를 줄여서 res로 쓰기도 합니다.
const promise = new Promise(res => res('Hello!!'));
promise.then((string) => {
console.log(string);
});
// console.log 결과
Hello!!
Promise {<resolved>: undefined}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: undefined
then
은 Promise
을 리턴하기 때문에 then
메서드를 연결하여 사용할 수 있습니다.
Promise.resolve('Hi!').then(string => {
return new Promise(res => {
string += ' My name is';
res(string)
});
}).then(string => {
string += ' Parkjihye';
console.log(string);
return string;
});
// console.log 출력
// Hi! My name is Parkjihye
먼저 Promise 처리가 완료된 이행값 string
을 then()
에서 받아 My name is
를 합친 후 Promise를 리턴하여 resolve
이행 콜백함수에 인자로 넣어 보냅니다.
여기까지 string은 Hi! My name is
입니다. Promise가 리턴되어 다시 then()
으로 string 값을 받아 Parkjihye
문자를 마지막으로 합쳐주었습니다.
const promise = new Promise(res => res('Hi!'));
promise.then(string => {
string += ' My name is';
return string;
}).then(string => {
string += ' Parkjihye';
console.log(string);
return string;
});
위 코드 역시 똑같은 값을 얻을 수 있습니다.
catch()
메서드는 Promise
실패되었을 때 실패 이유를 받아올 수 있습니다.
const promise = new Promise((res, rej) => rej('error'));
promise.then(result => console.log(result)).catch(error => console.log(error));
// console.log 출력
// error
image
엘리먼트를 생성하여 src
경로를 인자값으로 넣어서 image가 성공적으로 load 되었을때 엘리먼트를 받고, 실패되었을 때 error를 받는 함수를 만들어보겠습니다.
const imageLoader = (src, timeout) => new Promise((resolve, reject) => {
const image = new Image();
image.onload = () => resolve(image);
image.onerror = (error) => reject(error);
image.src = src;
setTimeout(resolve, timeout);
});
imageLoader('https://source.unsplash.com/user/erondu/1600x900', 500).then(result => console.log(result)).catch(error => console.log(error));
위 코드를 실행하면 image가 성공적으로 load가 되어 0.5초 뒤 image element를 반환해주고, src 주소를 잘못된 주소로 바꿔 실행하게 되면 image에 해당 src 주소가 잘못 되었기 때문에 이미지를 불러올 수 없어서 error가 콘솔에 나온다.