console.log('1번 작업 시작');
console.log('2번 작업 시작');
console.log('3번 작업 시작');
1번 작업 시작
2번 작업 시작
3번 작업 시작
console.log('1번 작업 시작');
setTimeout(() => {
console.log('2번 작업 (비동기) 시작');
}, 1000);
console.log('3번 작업 시작');
1번 작업 시작
3번 작업 시작
2번 작업 (비동기) 시작
동기: 작업이 순차적으로 실행되며, 하나의 작업이 끝나야 다음 작업이 실행된다. 특정 작업이 오래 걸리면, 그 이후의 작업들은 모두 지연된다.
비동기: 작업이 병렬적으로 실행될 수 있으며, 특정 작업이 완료되기를 기다리지 않고 다음 작업을 계속 진행한다.
function exampleTimer(callback) {
setTimeout(() => {
console.log('비동기 작업 완료');
callback();
}, 500);
}
exampleTimer(() => {
console.log('콜백 함수 실행');
});
0.5초 뒤에 비동기 작업을 완료하고 콜백 함수를 실행한다.
function exampleTask() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('작업 성공');
}, 1000);
});
}
exampleTask().then(result => {
console.log(result); // "작업 성공" 출력
}).catch(error => {
console.error(error);
});
기본적으로 Promise는 객체를 생성해주고 그 안에 2개의 인자 값을 받아오는데, 성공과 실패이다.
Promise의 작업해결을 resolve()에 넣어서 전달한다.
작업이 성공하면 <.then> 콜백을 실행하며, 실패하면 <.catch>를 실행한다.
var addCoffee = function (name) {
return new Promise(function (resolve) {
setTimeout(function(){
resolve(name);
}, 500);
});
};
var coffeeMaker = async function () {
var coffeeList = '';
var _addCoffee = async function (name) {
coffeeList += (coffeeList ? ', ' : '') + await addCoffee(name);
};
await _addCoffee('에스프레소');
console.log(coffeeList);
await _addCoffee('아메리카노');
console.log(coffeeList);
await _addCoffee('카페모카');
console.log(coffeeList);
await _addCoffee('카페라떼');
console.log(coffeeList);
};
coffeeMaker();
promise를 사용하는것은 동일하나 function 앞에 async를 붙여준다. 그리고 작업 대기는 await를 통해 await의 동작이 끝나기를 기다린다.