노드의 버전
Node js는 짝수 버전마다 메이저한 업그레이드를 진행한다. 이에 따라 LTS 버전이 되는 것은 짝수 버전이다.
프로미스
프로미스는 다음과 같이 작동한다.
먼저 새로운 프라미스 객체를 생성한다.
프라미스의 생성자 Promise()는 첫번째 인수로 resolve함수를, 두번째 인수로 reject함수를 갖는 콜백 함수를 매개변수로 갖는다.
const condition = true
const promise = new Promise((resolve, reject) => {
if (condition){
resolve('성공');
} else {
reject('실패');
}
});
프라미스 내부에서 resolve, reject가 호출될 수 있다.
promise의 기본 상태는 pending상태이다.
resolve가 호출되면, promise는 resolved상태가 되고, then이 실행된다.
reject가 호출되면, promise는 rejected상태가 되고, catch가 실행된다.
finally는 성공/실패 여부와 상관없이 실행된다.
promise
.then((messeage)=>{
console.log(message);
}.catch((error)=>{
console.error(error);
}.finally(()=>{
console.log('무조건');
}
- .then은 then(resolveFn(), catchFn())의 두 개의 콜백을 인자로 받으며, catch는 then(undefinded, catchFn())과 같은 역할을 한다.
- .then의 resolveFn()과 catchFn()은 resolved된 promise를 반환한다. 만일 catchFn()에서 rejected된 promise를 반환하고 싶을 때에는 throw new Error()로 새로운 에러 객체를 반환하면 된다.
따라서 위의 원리를 활용하여 아래와 같이 프라미스를 체이닝할 수 있다.
.then과 .catch 모두 이행된 프라미스를 반환하므로, 아래와 같이 .then으로 받는다.
const promise = new Promise((_, reject) => reject("거절되었다."));
promise
.catch((error) => {
console.error(error);
return "안녕";
})
.then((hello) => {
console.log(hello); //catch에서 반환된 '안녕'이 출력됨.
});
거절된 프라미스를 반환하고자 할 때에는 throw new Error를 사용하고,
해당 구분은 .catch, 혹은 .then의 두번째 인자로 받을 수 있다.
promise
.catch((error) => {
throw new Error(error);
return "안녕"; // 무효한 구문
})
.then((hello) => {
console.log(hello); //실행되지 않음
})
.catch((error) => {
console.log(error); //catch에서 발생한 에러 '거절되었다'가 출력됨.
});
async
프라미스를 다루는 또 다른 방법으로는 async-await와 try-catch를 조합하는 방법이 있다.
const promise = new Promise((_, reject) => reject("거절되었다."));
(async () => {
try {
const result = await promise; //await 키워드를 통해 promise가 settled될 때까지 기다린다.
console.log("실행됨");
console.log(result);
} catch (error) {
console.log("거절됨");
console.log(error);
}
})();
거절됨
거절되었다.
이때 async-await는 '순차적으로' 실행되므로, 비동기적으로 처리하는 기존 promise 체이닝 방식과는 성능상 차이가 있을 수 있다. 가령, '로그인'을 한 후, 유저 정보를 토대로 '회원 정보', '결제 내역', '팔로워 수' 등을 가져와야 하는 경우, await login, await 회원정보, await 결재내역, await 팔로워수 등으로 처리하면 매우 느리다.
REPL (Read, Eval, Print Loop)
자바스크립트는 컴파일하지 않고 즉석에서 실행하는 '스크립트' 언어이다. 따라서 코드를 '읽고', '해석하고', '반환하는' 작업을 '반복'할 수 있다. 이러한 역할을 하는 노드의 콘솔을 REPL이라 한다.
콘솔에서 'node'를 입력하면 프롬프트가 > 모양으로 바뀐다.
해당 상태에서 스크립트 코드를 입력할 수 있다.
.exit 키워드를 통해 종료할 수 있다.
% node
Welcome to Node.js v18.6.0.
Type ".help" for more information.
> const hello = "안녕"
undefined
> console.log("hello")
hello
undefined
> .exit
자바스크립트 파일 실행
node 파일경로
를 통해 자바스크립트를 실행할 수 있다.
% node test
거절되었다.
async 거절됨
거절되었다.
promise chaning 안녕