스레드에 작업을 맡긴 후 그 작업이 끝날 때까지 기다렸다가 다음 작업을 시작하는 것을 말한다. 즉 코드가 순서대로 실행된다.
console.log(1);
console.log(2);
console.log(3);
console.log(4);
//출력
/*
1
2
3
4
*/
스레드에 작업을 맡긴 후 기다리지 않고 다음 작업을 하는 것을 말한다.
console.log(1);
console.log(2);
setTimeout(function() {console.log(3)}, 5000);
console.log(4);
//출력
/*
1
2
4
3
*/
서버와 웹 브라우저가 통신을 할 때 사용된다. 만약 해당 요청의 시간이 오래 걸린다면 비동기식으로 데이터를 요청하고, 데이터가 도착하기 전에 다른 작업을 수행할 수 있습니다.
Promise는 어떤 연산, 비동기 연산이 최종적으로 완료 혹은 성공했는지 실패했는지 알려주는 객체입니다.
Primsise의 상태는 세가지다
pending : 무엇가를 기다리는 상태 -> Promise는 이 비동기적 값이 최종적으로 resolved일지 rejected일지 알려준다.
resolved : 연산이 성공한 상태
rejected : 연산이 실패한 상태
then : resolved 값을 처리한다.
catch : rejected 값을 처리한다.
//fetch 메소드의 리턴값은 프로미스 데이터 타입을 리턴한다.
//그리고 프로미스 데이터은 Response object를 돌려준다.
const fetched = fetch('https://jsonplaceholder.typicode.com/posts');
console.log(fetched); //Promise {<pending>}
fetched.then(function(resolved) {
console.log(resolved);
})
fetched.catch(function(rejected) {
console.log(rejected);
});
fetch('https://jsonplaceholder.typicode.com/posts')
.then(function(response) {
//console.log("response: " + response.json()); //Promise {<pending>}
// response.json().then(function(data) { //Nested promise
// console.log(data);
// })
return response.json(); //리턴하여 then과 then을 연결하는 방식을 promise chaining이라고 한다.
})
.then(function(data) {
console.log(data);
})
.catch(function(reason) {
console.log(reason);
});
콜백, Promise 체인의 단점은 async와 await로 보완할 수 있다.
async를 함수 앞에 붙이면 '이 함수는 비동기적인 함수이고 Promise를 반환한다.'라고 선언한다.
반환값이 Promise 생성 함수가 아니어도 반환되는 값을 Promise 객체에 넣는다.
await는 async 함수 안에만 사용할 수 있다. async 함수 외부에서 사용하면 에러가 발생한다. Promise를 반환하는 함수 앞에 await를 붙이면, 해당 Promise의 상태가 바뀔 때까지 코드가 기다린다. Promise가 성공 상태 또는 실패 상태로 바뀌기 전까지는 다음 연산을 시작하지 않는 것이다.
function timer(time) {
return new Promise(resolve => {
setTimeout(() => {
resolve(time);
}, time);
});
}
// console.log('start');
// timer(1000)
// .then((time) => {
// console.log('time: ' + time);
// return timer(time + 1000);
// })
// .then((time) => {
// console.log('time: ' + time);
// return timer(time + 1000);
// })
// .then((time) => {
// console.log('time: ' + time);
// console.log('end');
// })
const run = async () => {
console.log('start');
let time = await timer(1000);
console.log('time: ' + time);
time = await timer(1000);
console.log('time: ' + time);
time = await timer(1000);
console.log('time: ' + time);
console.log('end');
}