TIL.34 동기・비동기

조연정·2020년 10월 16일
0
post-thumbnail

동기와 비동기의 개념을 알아보고, 비동기의 하이라이트 'async'와 'await'에 대해서도 알아보자.

동기(Synchronous)・비동기(Asynchronous)

동기는 코드 순서대로 동작이 이루어지며, 비동기는 언제 코드가 실행될지 모른다. 앞에 있는 코드들이 많고 느리면 뒤에 있는 코드들이 기다린 상태로 나아갈 수 없어서 일을 효율적으로 처리할 수 없기 때문에 비동기 코드가 필요하다.

//1.동기
console.log('내가 첫번째로 나오지');
console.log('나는 두번째로 나오지');
console.log('나는 마지막으로 나오지');

//2.비동기
console.log('1');
setTimeout(() => 
	console.log('2'), 1000);
console.log('3');

//expected output
1
3
2

promise

'프로미스'는 자바스크립트 비동기 처리를 위한 객체이다.
가끔 쇼핑몰에서 스크롤을 빨리 하다가 돌아가는 톱니바퀴⚙️를 본 적이 있을 것이다. promise를 사용해 비동기를 동기화시켜준 것이다.
만약 비동기를 동기화시켜주지 않았다면, 사용자는 빈화면을 보게 될 것이다.

const condition = true; // true면 resolve, false면 reject 
const p = new Promise((resolve, reject) => {
	if (condition) {
    resolve('Success')
    } else {
    	reject('Fail')
   }
});

p.then((message) => {
console.log('This is in the then' + message)
}).catch((message) => {
console.log('This is in the catch' + message)
})
  • 만약 a가 2이면 'resolve', a가 2가 아니면 'reject'. 위에 경우에선 resolve 메소드를 불러올 것이다.
  • 리졸브('Success'리턴값)-> then을 불러오고, 리젝트('Failed'리턴값)-> catch를 불러온다.
  • then을 붙이면 결과를 반환하게 된다.실행이 완료되지 않았다면, 완료 후 then 내부 함수가 실행된다.
  • 'promise'는 코드를 분리할 수 있고, 콜백함수는 바로 붙어서 써줘야한다는 차이점이 있다.

async・await

async,await는 비동기의 하이라이트라고들 부른다. 기존의 비동기 처리방식인 콜백함수와 프로미스에서 업그레이드된 방법이라고 생각할 수 있다.


async function myAsync() {
	delayP(3).then(time) => {
    console.log(time);
    });
   return 'async'; 
}

//try-catch문 사용하기
const promise = new Promise(...)

promise.then((result) => ...)

async function main() {
	try {
    const result = await promise;
    return result;
    }catch (error) {
   	 console.error(error);
   }
 }

main().then((name) => ...)
  • async라는 예약어를 붙인다.
  • 함수의 내부 로직 중 비동기 처리 코드 앞에 await를 붙인다.
  • async.await의 경우, 'promise'가 실패하는 경우에 사용하는 'catch'가 없다. 그럴 때는 try로 감싸고, catch문을 넣어줘야 한다.

콜백지옥 해결하기

function findeAndSaveUser(IDs) {
	IDs.findOne({}, (err, id)) => { //첫번째 콜백
    if (err){
    	return console.error(err);
 }
 id.name = 'jyj';
 id.save((err) => { //두번째 콜백
 	if (err) {
    	return console.error(err);
      }
      IDs.findOne({gender: 'm'}, (err, id) => { //세번째 콜백
      })
    });
  }
}
//async,await 사용하기
async function findAndSaveUser(IDs) {
	let IDs = await IDs.findOne({});
  	id.name = 'jyj';
  	id = await id.save();
  	id = await IDs.findOne({gender: 'm'});
}

profile
Lv.1🌷

0개의 댓글