undefined
비동기식 함수 Promise/Async /Await 본문
반응형
1. 들어가기 이전
- 자바스크립트는 single thread *single thread = 한번에 한줄씩 코드가 실행됨
- 컴퓨터는 stack구조로써 콜백함수를 중첩적으로 이용하면 성능이 저하되어 UX에 좋지 않다. *stack = 값의 후입 선출
- single thread, 콜백중첩함수의 보완 => 비동기식 함수!
1. 비동기식 함수란?
코드의 값이 나올때 까지 기다리지 않고 브라우저에 코드를 보내면 브라우저가 대신 값을 처리해주고 그 값을 받아온다.
그 동안 다음 코드를 실행한다.
대표적인 내장형 비동기식 함수는 setTimeout() 이 있다.
ex) 1 실행 => 2 의 코드를 브라우저에 보냄 => 3실행(브라우저 10초 세는중) => 2 실행
console.log() // 1
setTimeout(()=>{},10000 // 2
console.log() // 3
2. .then .catch를 이용한 Promise 사용법 *세부적인 값들은 임의적인 값입니다.
const request = (url) => {
return new Promise((resolve, reject) => {
const delay = Math.floor(Math.random() * 5000) + 500;
setTimeout(() => {
if (delay > 4000) {
reject("connection fail");
} else {
resolve("connection success!");
}
}, delay);
});
};
// <1> then을 이용한 비동기식함수
request("asd.com/data1")
.then((data) => {
console.log(data);
return request();
})
.then((data) => {
console.log(data);
return request()
})
.then((data) => {
console.log(data);
})
.catch((e) => {
console.log("err is", e);
});
성공시 .then (return을 계속 해주면서 연쇄작용)
실패시 .catch (error를 인자로 받아 에러의 이유를 알 수 있다.)
3. async, await를 이용한 Promise 사용법 *세부적인 값들은 임의적인 값입니다.
const request = (url) => {
return new Promise((resolve, reject) => {
const delay = Math.floor(Math.random() * 5000) + 500;
setTimeout(() => {
if (delay > 4000) {
reject("connection fail");
} else {
resolve("connection success!");
}
}, delay);
});
};
// <2> async await를 이용한 비동기식 함수
const recievedRequest = async () => {
try {
const data1 = await request("data1");
console.log(data1);
const data2 = await request("data2");
console.log(data2);
} catch (e) {
console.log("Error!!!!");
console.log(e);
}
};
asyn = 자동으로 Promise함수를 리턴.
await = 그 줄이 실행이 완료된 후에 다음 줄이 진행된다.
반응형
'Javascript' 카테고리의 다른 글
class - Constructor, extends 와 super (0) | 2022.05.28 |
---|---|
API 와 AJAX (0) | 2022.05.26 |
for...of loop (0) | 2022.05.18 |
Method - splice, sort (0) | 2022.05.13 |
Comparison Operator (0) | 2022.05.12 |
Comments