필수 JavaScript 개념

Arrow Function
Class & Super
Asynchronous
Promise & Async Func

Arrow Function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Basic
function plusTwo(s){
return s+2;
}
// Arrow Function
plusTwo = (s)=>{
return s+2;
}

//함축
plusTwo = s => s+2;
console.log(plusTwo(10)) //12
-----------------------------------
//MAP & FILTER
arr = [1,2,3,4,5,6,7,8,9,14,323,223]
arr_map = arr.map(function(v){
return v*2
})
//Arrow Function
arr_map = arr.map(v => v*2)//2,4,6,8,10,12,14,16,18,26,646,446
arr_filter = arr.filter(v=>v>10)//14,323,223

Class & Super (클래스 상속)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//parent
class Animal{
constructor(leg){
this.leg = leg
}
printAnimal(){
console.log(this.name+"은 "+String(this.leg)+"개의 다리를 가진다.")
}
}

//child
class Lion extends Animal{
constructor(name, leg){
super(leg) //부모의 생성자 (constructor)
this.name =name
}
getName(){
console.log("내 이름은 "+ this.name)
}
}

myLion = new Lion("king",4)
myLion.getName() //내 이름은 king
myLion.printAnimal() //king은 4개의 다리를 갖는다.

Asynchronous(비동기성)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//callback 기본구조
//callBack -> 다 되면 알려줘 : 비동기의 문제점을 알려줌
function doSomethingElseAsync(callBack){
console.log('doSomethingElseAsync: Wait for half a sec.')
setTimeout(){ callBack();,500}
}
------------------------------------
function sayhello(name,byCallback){
setTimeout(()=>{
console.log(name+" 님 안 녕 하 세 요");
byCallback()
}, 2000);//(2초뒤에 실행)
}

sayhello('mike',function(){
console.log("안 녕 히 가 세 요")
}) //mike님 안녕하세요 2초뒤 안 녕 히 가 세 요

Promise & Async Func

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

/* new Promise((resolve, reject)=>{})
Resolve -> 성공 / 해결 -> .then()
Reject -> 거절 / 실패 -> .catch() */

function sayhello2(name){
return new Promise((resolve, reject)=>{
setTimeout(()=>{
console.log(name+" 님 안 녕 하 세 요")
resolve("그 만")
} ,3000)
})
}
sayhello2("Frank")
.then((v)=>console.log(v+" 안 녕 히 가 세 요"))
//Frank 안녕하세요 3초뒤 그 만 안 녕 히 가 세 요

/*
.then 대신에 씀
async func_name(p){
const result = await get_result(){}
}

*/

async function sayhelloBye(name){
loc = await sayhello2(name)
console.log(loc +" 안 녕 히 가 세 요")
}

sayhelloBye("Hyunsoo")
//Hyunsoo 안녕하세요 3초뒤 그 만 안 녕 히 가 세 요

정리

  1. 비동기의 문제를 해결하기 위한 callback
  2. 작업이 완료되면 알려주는 callback은 가독성이 좋지 X
  3. 완료를 약속하는 Promise 등장
  4. Then / Catch로 편리하게 사용
  5. 더 편리한 것 async / await