동기(Sync) 의 반댓말로, 웹페이지를 새로고침없이 데이터를 불러오는 방식이다.
필요한 부분만 업데이트 하기 때문에 속도와 성능 향상 가능
요청과 응답이 동시에 일어나지 않아도 되기 때문에 동시에 다른작업을 할 수 있다
JacaScript 비동기 처리에 사용되는 객체이다.
test(1)then((result) => {
console.log(1, result);
});
Pending(대기)
new Promise(function(resolve, reject){
});
Fulfilled(이행)
function getData() {
new Promise(function(resolve, reject){
var data = 100;
resolve(data);
});
}
/* <resolve() 의 결과 값 data 를 resolveData 로 받는다> */
getData().then(function(resolvedData) {
console.log(resolvedData); // 100
});
위의 Pending(대기) 상태에서 resolve 를 실행하면 이행(Fulfilled) 상태가 된다
then() 을 이용하여 처리 결과 값을 받을 수 있다
Rejected(실패)
function getData() {
new Promise(function(resolve, reject){
reject(new Error("Request is failed"));
});
}
/* <reject()의 결과 값 Error를 err에 받음> */
getData().then().catch(function(err) {
console.log(err); // Error: Request is failed
});
new Promise(function(resolve, reject){
setTimeout(function() {
resolve(1);
}, 2000);
})
.then(function(result) {
console.log(result); // 1
return result + 10;
})
.then(function(result) {
console.log(result); // 11
return result + 20;
})
.then(function(result) {
console.log(result); // 31
});
프로미스 객체 하나 생성 후 setTimeOut()를 이용하여 2초 후 resolve( ) 를 호출하는 예제
resolve() 가 호출되면 대기->이행 으로 넘어가며 첫 번째 .then() 의 로직으로 넘어간다 then(1) -> then(11) -> then(31) 으로 넘어가며 최종 결과 값 31
getData().then(
handleSuccess,
handleError
);
getData().then().catch();
// catch()로 오류를 감지하는 코드
function getData() {
return new Promise(function(resolve, reject) {
resolve('hi');
});
}
getData().then(function(result) {
console.log(result); // hi
throw new Error("Error in then()");
}).catch(function(err) {
console.log('then error : ', err); // then error : Error: Error in then()
});
Promise의 가독성이 안좋다는 단점을 보완해주며 디버깅이 쉬워진 비동기 처리방법
Promise 예시
const makeRequest = () =>
getJSON()
.then(data => {
console.log(data);
return "done";
})
makeRequest();
async/await 예시
const makeRequest = async () => {
console.log(await getJSON());
return "done";
}
makeRequest();
async 함수
async function asyncFunction() {
return 'Hello, world!';
}
await 키워드
async function asyncFunction() {
const result = await someAsyncOperation(); // 기다림
console.log(result);
}
async function fetchUser() {
try {
const response = await fetch('https://api.example.com/user');
const user = await response.json();
return user;
} catch (error) {
console.error('Error fetching user:', error);
throw new Error('Failed to fetch user.');
}
}
fetchUser()
.then((user) => {
console.log('Fetched user:', user);
})
.catch((error) => {
console.error('Fetch user failed:', error.message);
});
예시 2
async function fetchData() {
console.log('Fetching data...'); // 1. 로그 출력
// 비동기 작업: 2초 후에 'Data fetched!'를 반환
return new Promise((resolve) => {
setTimeout(() => {
resolve('Data fetched!'); // 2. 비동기 작업 완료
}, 2000);
});
}
async function processData() {
console.log('Processing data...'); // 4. 로그 출력
const data = await fetchData(); // 5. await: 비동기 작업 완료까지 기다림
console.log('Received data:', data); // 6. 로그 출력
}
console.log('Start'); // 0. 로그 출력
processData(); // 3. processData 호출
console.log('End'); // 7. 로그 출력
실행순서