비동기 처리

김형민·2021년 6월 1일
0

비동기(Asynchronous) 함수란? 자바스크립트는 싱글스레드이기 때문에 한 번에 하나의 작업만 수행할 수 있다. 이를 해결하기 위해 비동기가 생겼다. 비동기란 특정 코드의 처리가 끝나기 전에 다음 코드를 실행할 수 있는 것을 뜻한다.

console.log('1')
setTimeout(()=> console.log('2'), 1000) // 나중에(1초) 불러주는 callback함수
console.log('3')

콜백은 항상 비동기에만 쓰일까?

콜백도 두 가지로 나뉜다

  • 즉각적으로 동기적으로 쓰이는 Synchronous callback
function printImmediately(print){ //print라는 콜백을 받는다
	print()
}

printImmediately(()=> console.log('hello'))
  • 나중에 언제 실행될지 모르는 Asynchrounous callback
function printWithDelay(print, timeout){
	setTimeout(print, timeout);
}

printWithDelay(()=>console.log('aysnc callback'), 2000)
>>  console.log('aysnc callback')이 2초뒤 실행

모든 함수의 선언은 호이스팅 되기때문에
function printWithDelay(print, timeout){
setTimeout(print, timeout);
}
함수 선언은 사실 맨위로 가 있다!


await


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

async fuction getApple() {
	await delay(3000) // 3초뒤에 apple 반환
	return 'apple'
}

async fuction banana() {
	await delay(3000) // 3초뒤에 banana 반환
	return 'banana'
}
// 콜백지옥의 향기가 솔솔난다
function pickFruit(){
	return getApple()
    .then(apple => {
    	return getBanana()
        .then(banana => `${apple} + ${banana}`)
    })
}

pickFruit().then(console.log)

async, await로 간단하게 만들기

이렇게 순차적으로 진행하게 되면 3+3이 되서 비효율적이다

async function pickFruit(){

	try {
   	 	const apple = await getApple()
		const banana = await getBanana()
    } catch(){ //에러처리
    	console.log(error)
    }
    return `${apple} + ${banana}`
}

비효율을 개선해보자 - await 병렬처리

async function pickFruit(){
		const applePromise = getApple() //콜백끼리 서로 관계가 없을경우 가능
        const bananaPromise = getBanana()
   	 	const apple = await applePromise()
		const banana = await bananaPromise()
   
    return `${apple} + ${banana}`
}

위의 코드를 더 간결하게 해보자

function pickAllFruits () {
	return Promise.all([getApple(), getBanana()])
    .then(fruit => fruit.join(' + '))
}

pickAllFruit().then(console.log) 
// apple + banana 출력  

먼저 실행되는 값을 가져오고 싶다면?

서로 딜레이가 다르다는 가정하에 apple - 1초 / banana 2초

function pickOnlyOne() {
	return Promise.race([getApple, getBanana])
}

pickOnlyOne().then(console.log)
// apple만 출력된다
profile
항해 중인 개발자

0개의 댓글