Promise 이 만들어진 배경 : 콜백 헬' 이라고 불리는 지저분한 자바스크립트 코드의 해결책
- 내용이 실행은 되었지만 결과를 아직 반환하지 않은 객체
- Then 을 붙이면 결과를 반환함
- 실행이 완료되지 않았으면 완료된 후에 Then 내부 함수가 실행됨
- Resolve(성공리턴값) -> then 으로 연결
- Reject(실패리턴값) -> catch 로 연결
- Finally 부분은 무조건 실행됨
const condition = true; //true면 resolve, false이면 reject
const promise = new Promise((resolve, reject) => {
if(condition){
resolve("성공");
} else {
reject("실패");
}
});
//다른 코드가 들어갈 수 있음
promise
.then((message) => {
console.log(message); //성공(resolve)한 경우 실행
})
.catch((message) => {
console.log(message); //실패(reject)한 경우 실행
});
Promise.resolve (성공리턴값) : 바로 resolve 하는 프로미스
Promise.reject (실패리턴값) : 바로 reject 하는 프로미스
Promise.all(배열) : 여러 개의 프로미스를 동시에 실행
- 하나라도 실패하면 catch로 감
- allSettled 로 실패한 것만 추려낼 수 있음
async / await (에이씽크 / 어웨잇)
async function 의 도입
변수 = await 프로미스; 인 경우 프로미스가 resolve 된 값이 변수에 저장된다.
변수 await 값; 인 경우 그 값이 변수에 저장된다.
async function findAndSaveUser(Users) {
let user = await Users.findOne({});
user.name = 'zero';
user = await user.save();
user = await Users.findOne({ gender: 'm'});
//생략
}
++++++++
async 에서 return 한 값들은 무조건 then 으로 받아야한다.
async function main() {
try {
const result = await promise;
return 'yoo';
} catch (error) { //프로미스가 실패할 경우 reject해줘야해서 try catch로 감싸야한다.
console.error(error);
}
}
//방법1
main().then((name) => ...)
//방법2
//혹은 await는 프로미스이기 때문에 아래와 같이도 사용 가능
const name = await main();
++++++++++
for await of 문법도 생겼다...
'Node.js' 카테고리의 다른 글
| [Node.js] Node 버전 변경하기 (0) | 2023.11.06 |
|---|---|
| [Node.js]노드(Node.js)의 역할 (0) | 2023.11.06 |
| [Node.js]노드(Node.js)의 정의 및 특징 (0) | 2023.11.05 |