Javascript ES6: Promise

BakJiYeon·2022년 1월 28일
0

관련 포스팅

Promise 객체(Object)

Promise: 간편하게 비동기 작업을 처리해주는 자바스크립트 객체

Producer

  1. 생성
  • executor 콜백함수를 인자로 받는다
  • executor는 resolve, reject 2개의 콜백함수를 인자로 받는다
    - resolve와 reject는 하나의 인자만 받는다.
    : resolve(value), reject(error)

코드A

const getData = new Promise((resolve, reject)=>{
	resolve("🍎")
    	reject(new Error("Promise 객체 시험 강제 중단"))
})
  1. 실행
  • state:
    Pending -> Fullfilled

    혹은
    Pending -> Rejected

  • Promise가 생성되자마자 executor함수가 바로 실행된다.

  • pending state를 확인하고 싶다면 다음과 같이 해보자.
//case1
const getData = new Promise((resolve, reject)=>{
	 setTimeout(()=>resolve("🍎"), 3000)
})
getData.then((res)=>console.log(res))

//case2
const getData = (ms)=>{
    return new Promise(resolve => setTimeout(resolve, ms))
}
getData(3000).then(()=>console.log("3초 지연 후 실행"))

  • 변경된 state는 더 이상 변하지 않는다.(예: 코드A
    에서 resolve가 결과를 받아오면 reject는 실행되지 않는다)

Consumers

  1. 서버와의 통신이 성공/실패 하였을 때
  • then()메서드는 새로운 Promise 객체를 return한다.
    - Promise Chaining : 연쇄적으로 사용할 수 있다.
    const getData = new Promise(res=>res(5))
    getData
    .then((data)=>{
    	return data *= 10 //50
    })
    .then((data)=.{
        	return data *= 10 //500
    })
    .then((data)=.{
        	return data *= 10 //5000
    })
  • 성공/실패와 상관없이 finally가 실행된다.
doPromise
.then((받아온값)=>{
	return console.log(`당신은${받아온값}을 받아오는 데 성공하였습니다.`)
}).catch(error=>{
	return console.log(`오류가 발생하였습니다: ${error}`)
}).finally(()=>{
console.log("프로미스 객체 시험이 모두 완료되었습니다.")})

References
https://ko.javascript.info/promise-basics
https://www.youtube.com/watch?v=JB_yU6Oe2eE
https://joshua1988.github.io/web-development/javascript/promise-for-beginners/

profile
no tomorrow without joy

0개의 댓글