TIL_49_230105

young0_0·2023년 1월 5일
0

TIL

목록 보기
48/91

49일 차 회고

  • promise, async await

Promise

비동기 적인를 실행하기 위한 자바스크립트 object

상태 (state) - 성공, 실패

  1. pending(대기) → fulfilled(성공) or rejected(실패)

producer 생성

  1. 두가지의 콜백함수를 받는다.
    1. resolve 성공
    2. reject 실패
  2. 네트워크, 또는 파일을 읽어 올때 시간이 오래 걸릴경우에는 동기적으로 실행할 경우 다음 라인의 로직을 읽어 오지 않기 때문에 비동기적으로 처리 하는 것이 좋다.
  3. promise는 바로 실행되기 때문에 이벤트처리(클릭하여 실행되는)가 있는 경우에는 잘 활용해야 한다. 그렇지 않으면 불필요 하게 네트워크 통신이 계속해서 처리 된다.
const promise = new Promise ((resolve, reject)=>{
		setTimeout(()=>{
			resolve('ok'); //성공했을 경우 

			// reject(new Error('no network')) //실패했을 경우 
		},2000)
}) 

consumers 값을 받아옴 then, catch, finally

  1. then
    1. then 값을 받아와서 콜백함수를 전달한다.
    2. promise 가 성공적으로실행된 resolve안에 들어온 값을 value 안으로 넣어 실행한다.
  2. catch
    1. reject 로 error가 발생했을 경우
  3. finally
    1. 성공과 실패 상관없이 마지막에 호출된다.
Pormise
.then(value=> {
	console.log(value) // 'ok' //2초후 실행된다. 
})
.catch(error=>{
	console.log(error)
})
.finally(()=>{
	console.log('finally')
})

promise chaining

여러가지 then을 묶에서 다른 비동기적인 함수도 사용 할수 있다.

const fetchNumber = new Promise((resolve, reject)=>{
	setTime(()=>{
		resolve(1),1000);
	})
})

fetchNumber
.then(num => num *2)
.then(num => num *3)
.then(num=>{
		return new Promise((resolve, reject)=>{
			setTimeout(()=>rewoluve(nume -1), 1000)
		})
})
.then (num => console.log(num)) //5

async await

promise 를 좀 더 깔끔하게 사용 할수 있다.

무조건 async await를 사용 하는 것이 아니라 프로젝트 성향에 맞는 것을 찾아 쓰는 것이 좋다.

async

함수 앞에 async 를 붙히면 promise를 반환한다.


async function fetchUser(){
	return 'ellie'
}

const user = fetchUser()
user.then(console.log)

await

await는 async 라는 함수 안에 쓸수 있다. promise chaning 보다는 좀 더 가독성을 좋게 만들수 있다.

function delay(ms){
	return new Promise(resolve => setTimeout(resolve, ms))
}

async function getApple(){
	await delay(3000);
	return '사과'
}

async function getBanana(){
	await delay(3000);
	return '바나나'
}

//promise chaning 을 사용하다보면 콜백지옥처럼 문제점이 발생할수 있다.
function pickFruits(){
	return getApple().then(apple => {
		return getBanana().then(banana => `${apple} + ${banana}`)'
	})
}

pickFruits.then(console.log) // 사과 + 바나나

//async
async function pickFruits(){
	const apple = await getApple()
  const banana = await getBanana()
	return `${apple} + ${banana}`;

}
pickFruits().then(console.log) //사과 + 바나나

Promise API

promise.all

동시다발적으로 함수를 실행 해도 될때 promise.all 이라는 promise API를 사용한다,

//1. async 
async function pickFruits(){
	const applePromise = getApple()
	const bananaPromise = getBanana()
	const apple = await applePromise;
	const banana = await bananaPromise;
	return `${apple}+ ${banana}`
}
pickFruits().then(console.log) // 사과+바나나

//2. promise.all([]) 모든 프로미스가 병렬적으로 받을때 까지 기다린다.
function pickAllFruits(){
	return Promise.all([getApple(), getBanana()])
	.then(fruits => fruits.join(' + '))
}
pickAllFruits().then(console.log) //사과 + 바나나

promise.race

배열에 가장먼저 전달된 값을 리턴한다.

.
.
.

async function getApple(){
	await delay(2000);
	return '사과'
}

async function getBanana(){
	await delay(1000);
	return '바나나'
}
.
.
.

function pickOnlyOne(){
	return Promise.race([getAppple(), getBanana()])
}
pickOnlyOne().then(console.log) //바나나
profile
열심히 즐기자ㅏㅏㅏㅏㅏㅏㅏ😎

1개의 댓글

comment-user-thumbnail
2023년 1월 5일

async await는 항시 어렵네요 ㅠㅠ

답글 달기