변수사용 시 가끔 변수가 null일수 있다고 에러가 발생하는데 이때마다
if(변수){} 등의 null체크하기 번거로우니 컴파일러에게 이 변수는 절대 null, undefined일수 없다고
알려줄 필요가 있을 때 사용.
!!code -- false. 값이 boolean이 아니라도 0이나 undefined 등에 따라 true, false 반환
let code = null
!!code => false
let code = undefined
!!code => false
let code = 'data'
!!code => true
let code = 0
!!code => false
특정변수가 optional일 경우 사용
private test(code:string, name?:string){} // 호출 시 name 인자 생략 가능
null, undefinded 체크
let code = a ?? b -- a가 null, undefined라면 b
(a || b)의 차이는 a가 falsy한 모든 경우 b
null ?? 'code' => code
null || 'code' => code
0 ?? 'code' => 0
0 || 'code' => code
optional chaining
객체가 nullish 즉, undefined나 null인 경우에 TypeError 대신에 undefined 반환
user = {name: {first: "John", last: "Doe"}}
> user.address.street
Uncaught TypeError: Cannot read property 'street' of undefined
typeError 방지 하지 위해
if( user && user.address && user.address.street) {} 했지만
간단하게
user?.address?.street 로 표현
let n = '100'
console.log(+n); -- 변수앞에 +붙여주면 number type으로 변환
if(pr_prog_sts === 'A' || pr_prog_sts === 'B' || pr_prog_sts ==='C') ...
=>
if(['A','B','C'].includes(pr_prog_sts)) ...
promiseTest() {
return new Promise((resolve, reject) => {
if(성공){
resolve(10);
} else {
reject(...)
}
});
}
promiseTest.then(value) => {...성공}).catch(error => {...에러 });
// then도 promise이므로 리턴된 then에 catch를 달아줄 수 있다
finally도 추가할 수 있다.
promiseTest.then(value) => {...성공}).catch(error => {...에러 }.finally(()=>{...}));
// 병렬처리
AllPromise() {
return Promise.all([promiseTest1(),promiseTest2()]).then(1,2의 결과리턴 후 실행...)
}
// 요청값 중 먼저 결과가 반환 되는 것 리턴
onlyOnePromise() {
return Promise.race([promiseTest1(),promiseTest2()]).then(....)
}
primies.then().then().then() 처럼 순서대로 실행가능
// promise를 좀 더 간결하게 사용
async promiseTest() {
return 10;
}
async 추가 시 자동으로 promise로 변환.
//await은 async 함수 안에서만 사용가능.
async promiseTest() {
try{
await 서비스조회(); // 서비스의 반환값을 받을때까지 대기
}catch(...) {}
return 10;
}
// async/await가 더 간단하지만 병렬처리는 아래와 같이 더 지저분해짐
async getService1() {
await 서비스1();
return 리턴값
}
async getService2() {
await 서비스2();
return 리턴값
}
async callService() {
const firPromise = getService1();
const secPromise = getService2();
const firRtn = await firPromise;
const secPromise = await secPromise;
.....
}
=>