프로미스는 자바스크립트 비동기 처리에 사용되는 객체입니다. 프로미스는 주로 서버에서 받아온 데이터를 화면에 표시할 때 사용합니다.
function printAll(){
printString("A", () => {
printString("B", () => {
printString("C", () => {})
})
})
}
printAll()
function printAll(){
printString("A")
.then(() => {
return printString("B")
})
.then(() => {
return printString("C")
})
}
printAll()
new Promise(function(resolve, reject){
setTimeout(function() {
resolve(1);
}, 2000);
})
.then(function(result) {
console.log(result); // output 1
return result + 10;
})
.then(function(result) {
console.log(result); // output 11
return result + 20;
})
.then(function(result) {
console.log(result); // output 31
});
위 코드는 프로미스 객체를 하나 생성하고 setTimeout()을 이용해 2초 후에 resolve()를 호출하는 예제입니다.
resolve()가 호출되면 프로미스가 대기 상태에서 이행 상태로 넘어가기 때문에 첫 번째 .then()의 로직으로 넘어갑니다. 첫 번째 .then()에서는 이행된 결과 값 1을 받아서 10을 더한 후 그다음 .then() 으로 넘겨줍니다. 두 번째 .then()에서도 마찬가지로 바로 이전 프로미스의 결과 값 11을 받아서 20을 더하고 다음 .then()으로 넘겨줍니다. 마지막 .then()에서 종 결과 값 31을 출력합니다.
function getData() {
return new Promise(function (resolve, reject) {
reject('failed');
});
}
getData().then(function () {
}, function (err) {
console.log(err);
});
function getData() {
return new Promise(function (resolve, reject) {
reject('failed');
});
}
getData().then().catch(function (err) {
console.log(err);
});
참고
https://medium.com/front-end-weekly/callbacks-promises-and-async-await-ad4756e01d90
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise