-
Promise의 프로토타입 then과 catchjavascript 2020. 1. 31. 22:29
Promise.prototype.then(func1, func2)
Promise가 완료되면 then으로 연결된 함수를 실행한다. (callback후 callback을 연결하는 느낌!)
함수 두 개를 인자로 받는다.
Promise가 resolve면 func1이 실행되고, reject면 func2가 실행된다.
var p1 = new Promise(function (resolve, reject) { setTimeout(function () { resolve(); }, 1000); }); p1.then(function onFulfilled() { console.log('success'); // p1에서 resolve일 때 실행 }, function onRejected() { console.log('fail'); // p1에서 reject일 때 실행 });
Promise를 리턴한다 : 프라미스 체인
then() 메서드를 호출하면 새로운 Promise 객체가 반환된다.
리턴된 Promise에 then을 계속 이어 연속적으로 호출할 수 있다.p1.then(function one() { //.. }).then(function two() { //.. }).then(function three() { //.. });
resolve에서 넘겨준 인자를 받을 수 있다.
then에서 리턴된 값을, 다음 then에서 다시 인자로 받을 수도 있다.
var p1 = new Promise(function (resolve, reject) { setTimeout(function () { resolve(123); // then으로 인자 전달 }, 1000); }); p1.then(function one(data) { // resolve로부터 인자를 받음 console.log(data); // 123 return 456; // 다음 then으로 인자를 넘긴다. }).then(function two(data2) { console.log(data2); // 456 return 789; })
Promise.prototype.catch(func)
reject발생 시(then의 함수들 포함) 위의 함수들을 중단하고 바로 실행된다.
p1.then(function one() { //.. }).then(function two() { //.. }).catch(function onError() { // 앞에서 발생한 에러를 모두 모아서 보여줌 //.. })
Promise의 에러처리 - catch를 추천!
위에서 Promise 에러 처리방법으로 then의 두번째 인자로 처리하거나, catch메서드를 사용하는 것이 있었다.
그러나 then의 두번째 인자로 처리 시, 첫번째 콜백함수 내부에서 오류가 날 경우 아래와 같이 제대로 캐치하지 못하게 된다.function hi() { return new Promise(function(resolve, reject) { resolve('hi'); }); } hi().then(function(result) { console.log(result); throw new Error("then 내부에서 에러!"); // Uncaught (in promise) Error: Error in then() }, function(err) { console.log("then 내부에서 난 오류는", err); });
에러를 잡지 못했다. catch() 메서드 사용 시
function hi() { return new Promise(function(resolve, reject) { resolve('hi'); }); } hi().then(function(result) { console.log(result); throw new Error("then 내부에서 에러!"); // Uncaught (in promise) Error: Error in then() }).catch(function(err) { console
에러를 잡고 자연스럽게 처리했다. 'javascript' 카테고리의 다른 글
passport를 이용한 GitHub 로그인 (0) 2020.03.15 Learning JavaScript 후기 1 (0) 2020.02.02 Promise의 생김새와 3가지 상태 (0) 2020.01.31 자바스크립트에서 call, apply, bind (0) 2020.01.31 예측 가능한 콜백, Promise (0) 2020.01.30