동기와 비동기의 개념을 알아보고, 비동기의 하이라이트 'async'와 'await'에 대해서도 알아보자.
동기는 코드 순서대로 동작이 이루어지며, 비동기는 언제 코드가 실행될지 모른다. 앞에 있는 코드들이 많고 느리면 뒤에 있는 코드들이 기다린 상태로 나아갈 수 없어서 일을 효율적으로 처리할 수 없기 때문에 비동기 코드가 필요하다.
//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를 사용해 비동기를 동기화시켜준 것이다.
만약 비동기를 동기화시켜주지 않았다면, 사용자는 빈화면을 보게 될 것이다.
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)
})
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) => ...)
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'});
}