본문 바로가기
TIL/엘리스 SW 엔지니어 트랙 2기

[4주차] 20220427 엘리스 TIL (JavaScript 심화)

by VANAV 2022. 6. 30.

** JSON 프로퍼티의 키는 문자열 큰 따옴표로 묶어줘야 한다.

 

* db.json 의 내용을 변경한다고 바로 반영되지 않는다.

 

** json 저장소 생성 명령어(port 주소 조정해서 생성)

  • npx json-server --watch -p 3004 db.json
  • -p 3004 부분이 꼭 들어가야한다. 3004 부분이 주소 조정 부분

*** promise hell (callback hell)

fetch('http://localhost:3004/topics')
    .then(function(response){
        return response.json();
    })
    .then(function(topics){
        let firstId = topics[0].id;
        fetch('http://localhost:3004/topics/'+firstId)
            .then(function(response){
                return response.json();
            })
            .then(function(topic){
                console.log('topic', topic);
            })
    });
  • 이렇게 코드를 적는다면? 콜백함수 안의 콜백함수... (callback hell 이다)
fetch('http://localhost:3004/topics')
.then(function(response){ return response.json(); })
.then(function(topics){
let firstId = topics[0].id;
console.log(firstId); });
 
  • 여기서 fetch의 데이터가 어디에 담길까? => response 변수에 담김
response = await fetch('http://localhost:3004/topics%27)
  • fetch 리턴값 = promise
  • promise 리턴값에 await를 붙이면 파라미터의 response에 리턴한다.
  • 우리가 response.json() 을 실행하면 promise 를 리턴한다.

결론적으로,

fetch('http://localhost:3004/topics%27)
.then(function(response){ return response.json(); })
response = await fetch('http://localhost:3004/topics%27)

는 같다. (코드가 상당히 축약됨)

 

fetch('http://localhost:3004/topics')
    .then(function(response)){
    })
    .then(function(topics){
        let firstId = topics[0].id;
        console.log(firstId
)})
let response = await fetch('http://localhost:3004/topics')
let topics = await response.json();
console.log(topics);

이 두 코드들도 똑같이!!! 동작한다

 

// 코드 1
console.log(1);
fetch('http://localhost:3004/topics')
    .then(function(response)){
    })
    .then(function(topics){
        let firstId = topics[0].id;
        console.log(firstId
)});
console.log(2);

// 코드 2
console.log(1);
response = await fetch('http://localhost:3000/topics');
topics = await response.json();
console.log(topics);
console.log(2);
await는 동기적인 느낌이 있기 때문에 이 경우 코드 2 에서는 console(1) 이 실행되고,
중간 코드가 다 실행되고 나서 console(2) 가 실행된다. 따라서 어떤 경우에는 성능적으로 코드 1 이 더 좋을 수 있다.
 
 
 
 
 

댓글