728x90

1. JavaScript Engine

Call Stack(호출 스택) : 코드들이 짜여진 순서대로 한 줄 한 줄 들어가서 실행되는 공간(single threaded : 한 번에 코드 한번 수행 가능)

Heap : 변수, 함수 등이 할당되는 공간

 

2. Web APIs

setTimeout과 같은 비동기 함수들(APIs)이 정의되어 있는 영역

비동기 함수들이 Call Stack에 들어오면 Web API 영역으로 이동된다고 생각하자. 

이러한 비동기 함수들은 작업이 완료되면 callback 함수를 callback queue에 추가한다. 

 

3. Callback Queue

비동기 함수 작업이 완료된 후, 실행이 되기 위해 다시 Call Stack에 들어가기 전에 대기하는 영역.

해당 함수가 어떤 형태이냐에 따라서 대기 순서가 바뀌는데 순서는 아래와 같다.

1. Microtask Queue(Job Queue) : Promise 함수

2. Animation Frames

3. Task Queue(Event Queue) : setTimeout 함수

console.log(1);

setTimeout(() => console.log("setTimeout"));

Promise.resolve() //
  .then(() => console.log("Promise"));

console.log(2);

// 결과값
// 1
// 2
// "Promise"
// "setTimeout"

 

4. Event Loop

call stack에 작업중인 코드가 있는지 없는지 확인하는 과정.

call stack에 작업중인 코드가 없다면, callback queue에 대기하고 있던 작업들(콜백 함수)을 꺼내와서 call stack에 넘겨주는 역할을 한다.

 

5. JavaScript 내부 동작 원리 간단 정리

JavaScript는 기본적으로 웹 페이지를 작동시키기 위한 프로그래밍 언어이다. 웹페이지는 거의 즉각적이어야 한다.

JavaScript는 동기적으로 작동한다. 한 줄 한 줄(call stack).

그런데 즉각적으로 수행되지 못하는 코드들이 있다.(setTimeout, promise 등등)

그래서 JavaScript는 시간이 오래 걸리는 작업들을 Web APIs에게 넘겨버렸다. 

이러한 코드들은 작업이 완료되면 콜백함수를 callback queue에 추가한다. 

callback queue에 들어온 콜백함수들이 call stack에 들어가서 실행되기 위해서는 call stack에서 작업 중인 코드가 있는지 없는지 확인이 필요하다.

이러한 확인 절차를 거쳐 call stack에 아무것도 없을때 콜백 함수를 call stack에 추가해주는 것이 바로 event loop다. 

 

참고 자료

자바스크립트와 이벤트 루프

우리밋_woorimIT

코딩애플

반응형
728x90

1. 동기(synchronous)와 비동기(asynchronous)

동기란, 호이스팅(선언이 제일 위로 올라가는 것)이 된 이후부터 코드가 작성된 순서대로 작동한다는 의미이다. 

동기란 말을 처음 들었을 때는 동기화란 단어가 생각이 나서 "어떤 작업이 동시에 같이 일어나는 것인가?"라 생각을 했었는데, 전혀 다르다.

반면 비동기는 JavaScript의 동기적인 특성인 코드가 작성된 순서를 따르지 않고, 특정 요청에 의해 해당 코드에 지연이 발생하더라도 기다리지 않고 바로 이어서 다음 코드를 실행한다는 의미이다. 

// Synchronous
function first() {
  console.log("first"); // 첫번째로 실행되고,
}
function second() {
  console.log("second"); // 이어서 바로 실행된다. 
}
first()
second()
	
// Asynchronous
function first() {
  setTimeout(() => console.log(first), 5000); 
  // first 함수가 호출되고, 5초 동안 기다린 다음 결과값을 출력하고, 그 다음으로 second 함수가 실행되는게 아니다.
}
function second() {
  console.log("second"); 
  // first 함수가 호출되고, 5초의 시간이 흐르는 사이에 second 함수를 실행하고, 이후에 first 함수의 결과값이 출력된다.
}
first()
second()

 

2. callback(콜백)

callback 함수는 다른 함수가 실행을 끝낸 뒤 실행되는 즉, call back 되는 함수를 말한다.

함수의 parameter(매개변수)로 들어가서 실행되는 함수이다.

// Synchronous callback
function synchronousPrint(print) {
  print();
}
synchronousPrint(() => console.log("hello")); 
// hello를 출력하는 함수를 인자(argument)로 synchronous 함수에 전달 ==> 곧바로 synchronous 함수 실행(동기)

// Asynchronous callback
function asynchronousPrint(print, timeout) {
  setTimeout(print, timeout);
}
asynchronosPrint(() => console.log("hello"), 2000); 
// hello를 출력하는 함수를 인자(argument)로 asynchronous 함수에 전달 ==> 2초 후 asynchronous 함수 실행(비동기)

callback hell(콜백지옥)의 문제점 

1. 가독성이 떨어진다. => 어디서 어떻게 연결되어지는지 한눈에 알아보기 힘들다. 

2. 디버깅, 에러 분석, 유지/보수가 어렵다. 1번 이유때문.

 

3. Promise

Promise란?

JavaScript에서 제공하는 비동기를 간편하게 처리할 수 있도록 도와주는 object(객체)

네트워크 통신을 하거나, 파일을 읽어오는 행위 등 시간이 걸리는 일들은 promise를 만들어서 비동기적(병렬로 처리한다고 이해하면 쉬울 것 같다.)으로 처리하는 것이 좋다. 

Promise의 state는 뭘까?

promise의 state란 promise의 처리 과정을 의미한다.

기능이 수행 중인지(pending), 완료가 되어서 성공했는지(fulfilled), 실패했는지(rejected)를 나타내는 상태

Producer, Consumers란?

// 1. Producer(원하는 기능을 수행해서 해당하는 데이터를 만들어낸다.)
// Promise가 생성되면 자동적으로 실행된다.
const promise = new Promise((resolve, reject) => {
  console.log("doing somthing...");
  setTimeout(() => {
    resolve("Hello, World!"); // 콜백 함수의 인자 resolve를 호출하면 이행(fulfilled) 상태가 된다.
    // reject(new Error("no network")); // reject를 호출하면 실패(rejected) 상태가 된다. 
  }, 2000);
});

// 2. Consumers(원하는 데이터를 소비한다): then, catch, finally
promise
  .then((value) => {
    console.log(value);
  }) // 이행(fulfilled) 상태가 되면 then()을 이용하여 처리 결과 값을 받는다. 
  .catch((error) => {
    console.log(error);
  }) // 실패(rejected) 상태가 되면 catch()를 이용하여 처리 결과 값을 받는다. 
  .finally(() => {
    console.log("Done");
  }); // promise 이행/실패에 상관없이 마지막에 호출되어진다.

Promise chaining이란?

여러 개의 promise를 연결하는 것.

const fetchNumber = new Promise((resolve, reject) => {
  setTimeout(() => resolve(1), 1000);
}); // 이행 상태가 되어 1초뒤 resolve에 값이 들어온다. 

fetchNumber
  .then((num) => num * 2) // num parameter(매개변수)에 1이 들어오고 해당 콜백함수를 수행한 결과 값 2를 리턴한다.
  .then((num) => num * 3) // num parameter(매개변수)에 2가 들어오고 해당 콜백함수를 수행한 결과 값 6을 리턴한다.
  .then((num) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => resolve(num - 1), 1000);
    });
  }) // 새로운 promise를 만들어 1초 뒤 resolve에 5가 들어온다. 
  .then((num) => console.log(num)); // num parameter(매개변수)에 5가 들어오고 해당 콜백함수를 수행한다.

 

4. async/await

async와 await 이란? 

깔끔하게 promise를 사용할 수 있는 방법

Syntactic sugar

기능은 동일하지만 더 간결한 코드를 사용함으로써 직관성/편의성을 높여주는 프로그래밍 문법

ex) 삼항 연산자(Conditional (ternary) operator), 애로우 함수(arrow function), async 등등

async 사용 방법

// 기존 promise 사용 방법
function fetchUser() {
  return new Promise((resolve, reject) => {
    // do network request in 10 secs...
    resolve("ellie");
  });
}

// async 사용 방법(async = Syntactic sugar), 함수 앞에 async라는 키워드만 넣어주면 끝.
async function fetchUser() {
  // do network request in 10 secs...
  return "ellie";
}

const user = fetchUser();
user.then(console.log);
console.log(user);

await 사용 방법

// delay를 주는 promise 생성
function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

// 1초뒤 🍎를 받아오는 promise를 async 기능을 사용해서 생성
async function getApple() { // await 키워드는 async가 붙은 함수 안에서만 사용 가능
  await delay(1000);
  return "🍎";
}

// 1초뒤 🍌를 받아오는 promise를 async 기능을 사용해서 생성
async function getBanana() { 
  await delay(1000);
  return "🍌";
}

// 기존 promise를 사용해서 결과 값을 받아오는 방법(callback 지옥과 다를바 없다.)
function pickFruits() {
  return getApple().then((apple) => {
    return getBanana().then((banana) => `${apple} + ${banana}`);
  });
}

// await를 사용해서 결과 값을 받아오는 방법
async function pickFruits() {
  // JavaScript 특성상 동기적으로 🍎, 🍌의 promise를 실행할텐데,(2초가 걸리겠지)
  // 둘 사이의 연관성이 없다면 굳이 동기적으로 받아올 필요가 없다.
  // 따라서 Promise가 생성되면 자동적으로 실행되는 특징을 이용해서 변수(아래 두줄)를 생성해준다.
  // 두 함수가 동시에 실행되므로 시간 단축!(1초!)
  const applePromise = getApple();
  const bananaPromise = getBanana();
  const apple = await applePromise;
  const banana = await bananaPromise;
  return `${apple} + ${banana}`;
}

// 유용한 promise API: Promise.all(모든 promise들이 병렬적으로 작동해서 배열에 전달된다.)
function pickAllFruits() {
  return Promise.all([getApple(), getBanana()]) //
    .then((fruits) => fruits.join(" + "));
}

// 유용한 promise API: Promise.race(배열에 가장 먼저 전달된 promise 값을 받아온다.)
function pickOnlyOne() {
  return Promise.race([getApple(), getBanana()]);
}

 

참고 자료

드림 코딩 유튜브 - 자바스크립트 11~13

Evans Library

[번역] JavaScript: 도대체 콜백이 뭔데?

 

반응형
728x90

export default

1. 일반적으로 해당 모듈엔 하나의 개체(변수, 클래스, 함수 등)만 있다는 의미로 받아들여진다. 

2. 따라서 해당 모듈의 전체 개체를 export 한다는 의미를 갖는다.

3. 원하는 이름으로 import가 가능하다.(ex. import ThisIsSample from "경로")

// Data.js

function Data() {
  return <h1>Hello, React!</h1>;
}

export default Data;


// DataChild.js

import Data from "./Data"

 

export

1. 복수의 개체가 있는 라이브러리 형태의 모듈에서 가져오기 할 때 사용된다.

2. 특정 개체만 가져오는게 가능하다. 

3. 원하는 이름으로 import가 불가능하다.

// Robot.js

function Robot() {
  return <h1>Hello, React!</h1>;
}

function Robot2() {
  return <h1>Who are you??</h1>;
}

export Robot2;


// RobotChild.js

import { Robot2 } from "./Robot.js"
반응형

'Programming > React' 카테고리의 다른 글

[React]Frontend 초기 세팅  (0) 2022.02.04
[React.js]Link로 props 전달하기  (0) 2022.01.13
[React.js]React.memo() 알아보기  (0) 2021.12.26
728x90

git clone과 git pull의 차이는 내가 해당 프로젝트에 참여하고 있느냐 아니냐로 갈리는 것 같다.

 

git clone의 경우 해당 repository를 통째로 다운 받는 개념으로 내 컴퓨터에 해당 프로젝트의 폴더를 새롭게 생성을 하는데,

git pull의 경우는 내가 참여하고 있는 프로젝트에서 변경 사항이 생긴 경우 내가 로컬로 작업하고 있는 프로젝트와의 병합을 위해서 수행한다.

 

기술적인 부분은 김코더 김주역님 웹페이지를 참고하자.

반응형
728x90

1. sessionStorage란?

sessionStorage에 대한 자세한 설명은 아래의 두 사이트를 참고.

쓸데없는 코딩하기
 

[javascript] 세션 스토리지 알고 사용하기

관련지식 javascript, storage, session storage, polyfill 사용자가 로그인을 하고 로그아웃을 할 때까지만 사용되어야 하는 값은 임시적으로 필요하지만 로그인 중에는 지속성 있게 유지가 될 필요가 있습

sub0709.tistory.com

모던 JavaScript 튜토리얼
 

localStorage와 sessionStorage

 

ko.javascript.info

 

2. sessionStorage 간단 사용

아래 그림과 같이 input tag에 댓글을 달면 로그인 시 사용한 이메일 정보(sessionStorage)와 댓글이 입력되는 웹페이지를 구현한다고 했을 때, login.html에서 수집한 이메일 정보를 review.html에서 사용하기 위해서는 이메일 정보가 지속성 있게 유지될 필요가 있다. 

review.html 페이지
login.html 페이지

sessionStorage 객체를 이용하면 이를 손쉽게 구현할 수 있다.

login.html과 연동된 login.js에 아래와 같은 코드를 입력하고, 

// login.js

let id = document.getElementById("emailInput"); 
// 이메일정보가 입력되는 input tag의 id(혹은 class)를 불러온다.

sessionStorage.setItem("ID", id.value);
// sessionStorage에 해당 정보의 값을 저장한다.

댓글이 작성될 review.html과 연동된 review.js에 아래와 같은 코드를 입력한다. 이 후에 해당 값을 원하는 대로 사용하면 끝!

// review.js

let yourID = sessionStorage.getItem("ID");
// sessionStorage에 저장된 이메일 정보 값을 review.js에서 불러온다.

 

개발자 도구에서 살펴보면 아래 그림과같이 Application 탭의 Session Storage에 해당 값이 저장되어 있는 것을 확인할 수 있다. 

반응형
728x90

13. 비동기의 꽃 JavaScript async 와 await 그리고 유용한 Promise APIs | 프론트엔드 개발자 입문편 (JavaScript ES6)

// async & await
// clear style of using promise :)

// 1. async
// function fetchUser() {
//   return new Promise((resolve, reject) => {
//     // do network request in 10 secs...
//     resolve("ellie");
//   });
// }

async function fetchUser() {
  // do network request in 10 secs...
  return "ellie";
}

const user = fetchUser();
user.then(console.log);
console.log(user);

// 2. await
function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function getApple() {
  await delay(2000);
  return "🍎";
}

async function getBanana() {
  await delay(1000);
  return "🍌";
}

// function pickFruits() {
//   return getApple().then((apple) => {
//     return getBanana().then((banana) => `${apple} + ${banana}`);
//   });
// }

async function pickFruits() {
  const applePromise = getApple();
  const bananaPromise = getBanana();
  const apple = await applePromise;
  const banana = await bananaPromise;
  return `${apple} + ${banana}`;
}

pickFruits().then(console.log);

// 3. useful Promise APIs
function pickAllFruits() {
  return Promise.all([getApple(), getBanana()]).then((fruits) =>
    fruits.join(" + ")
  );
}

pickAllFruits().then(console.log);

function pickOnlyOne() {
  return Promise.race([getApple(), getBanana()]);
}

pickOnlyOne().then(console.log);
반응형
728x90

12. 프로미스 개념부터 활용까지 JavaScript Promise | 프론트엔드 개발자 입문편 (JavaScript ES6)

// promise.js

"use strict";

// Promise is a JavaScript object for asynchronous operation.
// State: pending -> fulfilled or rejected
// Producer vs Comsumer

// 1. Producer
// when new Promise is created, the executor runs automatically.
const promise = new Promise((resolve, reject) => {
  // doing some heavy work (network, read files)
  console.log("doing somthing...");
  setTimeout(() => {
    resolve("ellie");
    // reject(new Error("no network"));
  }, 2000);
});

// 2. Consumers: then, catch, finally
promise //
  .then((value) => {
    console.log(value);
  })
  .catch((error) => {
    console.log(error);
  })
  .finally(() => {
    console.log("Done");
  });

//   3. Promise chaining
const fetchNumber = new Promise((resolve, reject) => {
  setTimeout(() => resolve(1), 1000);
});

fetchNumber
  .then((num) => num * 2)
  .then((num) => num * 3)
  .then((num) => {
    return new Promise((resolve, reject) => {
      setTimeout(() => resolve(num - 1), 1000);
    });
  })
  .then((num) => console.log(num));

//   4. Error Handling
const getHen = () =>
  new Promise((resolve, reject) => {
    setTimeout(() => resolve("Chicken"), 1000);
  });
const getEgg = (hen) =>
  new Promise((resolve, reject) => {
    // setTimeout(() => resolve(`${hen} => Egg`), 1000);
    setTimeout(() => reject(new Error(`error! ${hen} => Egg`)));
  });
const cook = (egg) =>
  new Promise((resolve, reject) => {
    setTimeout(() => resolve(`${egg} => Egg fry`), 1000);
  });

getHen() //
  //   .then((hen) => getEgg(hen))
  .then(getEgg)
  //   .then((egg) => cook(egg))
  .catch((error) => {
    return "Bread";
  })
  .then(cook)
  //   .then((meal) => console.log(meal));
  .then(console.log)
  .catch(console.log);
// callback-to-promise.js

// Callback Hell example
class UserStorage {
  loginUser(id, password) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (
          (id === "ellie" && password === "dream") ||
          (id === "coder" && password === "academy")
        ) {
          resolve(id);
        } else {
          reject(new Error("not found"));
        }
      }, 2000);
    });
  }

  getRoles(user) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (user === "ellie") {
          resolve({ name: "ellie", role: "admin" });
        } else {
          reject(new Error("no access"));
        }
      }, 1000);
    });
  }
}

const userStorage = new UserStorage();
const id = prompt("enter your id");
const password = prompt("enter your password");
userStorage //
  .loginUser(id, password)
  .then(userStorage.getRoles)
  .then((user) => alert(`Hello ${user.name}, you have a ${user.role} role`))
  .catch(console.log);
반응형
728x90

display

CSS의 display 속성은 웹페이지를 어떻게 사용자에게 보여줄지를 결정한다. 

주요 속성값으로 inline, block, inline-block, none 이 있다. 

 

1. inline

width와 height을 지정할 수 없고, 오직 내용(contents)만 포함하는 개념이다.

줄 바꿈이 일어나지 않는다.

대표적으로 span, b, a tag 등이 있다.

 

2. block

가로 크기만큼의 영역을 모두 차지하고, 줄 바꿈이 일어난다.

width와 height의 크기를 지정할 수 있다. 

대표적으로 div, p, h tag 등이 있다. 

 

3. inline-block

inline과 block의 속성을 가지고 있다.

줄 바꿈이 일어나지 않지만, width와 height 크기 조절이 가능하다. 

 

4. Code

//HTML 

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="./index.css" />
  </head>
  <body>
    <div class="block_div">block</div>
    <div class="inline_div">inline</div>
    <div class="inline-block_div">inline-block</div>
  </body>
</html>
// CSS

body div {
  font-size: large;
  margin-bottom: 50px;
}
.block_div {
  display: block;
  background-color: aqua;
}
.inline_div {
  display: inline;
  width: 500px;
  /* inline 속성의 특징으로 위 속성값은 적용되지 않는다.  */
  background-color: chartreuse;
}
.inline-block_div {
  display: inline-block;
  width: 500px;
  background-color: gold;
}

Result

 

반응형
728x90

Semantic Web(a.k.a Web 3.0)이란??

W3C(World Wide Web Consortium)에서 제정한 World Wide Web의 확장판.

Semantic Web의 목적은 웹의 각종 정보들에 의미를 가지게 하기 위함이다. 여기서 의미를 가진다라고 함은 메타데이터(metadata)[각주:1]를 뜻한다. 메타데이터가 되기 위해서는 semantic tag가 필요하다. 

 

Semantic Tag란?

검색 엔진에 노출되기 위해서는 검색 키워드에 대응하는 인덱스가 존재해야하는데, 이러한 인덱스를 수집하는 기준이 바로 HTML의 semantic tag들이다.

HTML의 수많은 tag들중, img, header, main, body, footer 등이 바로 semantic tag들이다.

 

사이트에 이미지를 넣는 두 가지 방법

<img> VS <div> + background-image[각주:2]

두 가지 방법 모두 화면에 이미지를 구현한다는 점에서는 동일하지만, semantic 관점에서 차이가 있다. 

<img> 태그 - 의미를 가지고 있는 사진

<img alt="HTML" height="280" width="180" src="https://XXX">

1. 회사 로고, 인물 프로필 사진 등 콘텐츠 정보와 연관이 있는 이미지를 쓸 때 (alt 속성 함께 사용)

2. 경고 아이콘과 같이 중요한 의미가 내포된 이미지를 쓸 때 (마찬가지로 alt 속성 함께 사용)

3. 페이지 프린트시 이미지가 함께 나오도록 할 때

<div> 태그 + background-image 속성을 쓸 때 - "의미가 없어도 되는 사진"

// html
<div class="bg-img">배경이미지</div>
// CSS
.bg-img {
  /* background-color: yellow; */
  background-image: url("https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/HTML5_logo_and_wordmark.svg/1280px-HTML5_logo_and_wordmark.svg.png");
  height: 300px;
  width: 300px;
  background-size: 100%;
}

1. 이미지가 콘텐츠의 일부가 아닐 때

2. 이미지 스프라이트를 이용할 때

3. 말그대로 웹문서의 배경을 채우기 위한 용도일 때

4. 페이지 프린트시 이미지가 나오지 않게 할 때

 

 

  1. 메타데이터(metadata)는 데이터(data)에 대한 데이터이다. 이렇게 흔히들 간단히 정의하지만 엄격하게는, Karen Coyle에 의하면 "어떤 목적을 가지고 만들어진 데이터(Constructed data with a purpose)"라고도 정의한다.(wikipedia) [본문으로]
  2. 불타는 키보드 [본문으로]
반응형
728x90

script 태그란?

<script> 태그는 자바스크립트와 같은 클라이언트 사이드 스크립트(client-side scripts)를 정의할 때 사용

 

[references]

http://tcpschool.com/html-tags/script

 

script 태그의 위치에 따른 차이점

1. script 태그가 head 태그 안에 있을 때

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Document</title>
    <script src="test.js"></script> // script 태그가 head 태그 안에 위치
  </head>
  <body></body>
</html>

script 태그가 head 태그 안에 있을 때

js 파일 사이즈가 크거나, 인터넷 환경이 느릴 때 사용자가 웹사이트를 로딩하는데 시간이 오래 걸린다.

따라서 script를 head 태그에 포함하는 것은 좋은 선택은 아니다. 

 

2. script 태그가 body 태그의 제일 하단에 위치해 있을 때

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Document</title>
  </head>
  <body>
    <div></div>
    <script src="test.js"></script> // script 태그가 body 태그의 하단에 위치
  </body>
</html>

html이 모두 준비가 된 후에 javascript를 실행한다. 

사용자가 기본적인 html 컨텐츠를 빨리 볼 수 있는 장점이 있지만, 해당 웹사이트가 javascript에 의존적이라면 의미 있는 웹페이지를 보기까지 시간이 오래 걸린다. 

 

3. script 태그가 head 태그 안에 있지만, async 속성 값을 사용한 경우

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Document</title>
    <script async src="test.js"></script> // async 속성값을 사용
  </head>
  <body>
    <div></div>
  </body>
</html>

async 속성을 사용할 경우, 위 사진과 같이 html 파싱과 javascript 다운로드를 병렬로 수행한다. 다만 javascript 다운로드가 완료되면 html 파싱을 중지하고, 다운로드된 javascript 파일을 먼저 수행한 후, 나머지 html을 파싱한다. 

 

병렬로 진행되기 때문에 웹사이트를 불러오는 속도를 조금 빠르게 할 순 있지만, html이 파싱되기 전에 javascript가 동작하므로 javascript에 html과 상호작용하는 코드가 있을 경우 제대로 작동하지 않을 가능성이 있다.

 

4. script 태그가 head 태그 안에 있지만, defer 속성값을 사용한 경우

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Document</title>
    <script defer src="test.js"></script> // defer 속성값을 사용 
  </head>
  <body>
    <div></div>
  </body>
</html>

async와 동일하게 html 파싱중에 javascript 다운로드가 병렬적으로 진행된다. 그러나 async와 다르게 html 파싱이 모두 종료된 후에 javascript 명령을 수행한다.

 

[references]

드림코딩 : script async와 defer의 차이점

반응형
728x90

11. 비동기 처리의 시작 콜백 이해하기, 콜백 지옥 체험 😱 JavaScript Callback | 프론트엔드 개발자 입문편 (JavaScript ES6)

"use strict";

// JavaScript is synchronous.
// Execute the code block in order after hoisting.
// hoisting: var, function declaration // 변수나 함수를 제일 위로 끌어올려 주는 것
console.log("1"); // 동기
// setTimeout(function () {
//   console.log("2");
// }, 1000);
setTimeout(() => console.log("2"), 1000); // 비동기
console.log("3"); // 동기

// Synchronous callback
function printImmediately(print) {
  print();
}
printImmediately(() => console.log("hello")); // 동기

// Asynchronous callback
function printWithDelay(print, timeout) {
  setTimeout(print, timeout);
}
printWithDelay(() => console.log("async callback"), 2000); // 비동기

// Callback Hell example
class UserStorage {
  loginUser(id, password, onSuccess, onError) {
    setTimeout(() => {
      if (
        (id === "ellie" && password === "dream") ||
        (id === "coder" && password === "academy")
      ) {
        onSuccess(id);
      } else {
        onError(new Error("not found"));
      }
    }, 2000);
  }

  getRoles(user, onSuccess, onError) {
    setTimeout(() => {
      if (user === "ellie") {
        onSuccess({ name: "ellie", role: "admin" });
      } else {
        onError(new Error("no access"));
      }
    }, 1000);
  }
}

const userStorage = new UserStorage();
const id = prompt("enter your id");
const password = prompt("enter your password");
userStorage.loginUser(
  id,
  password,
  (user) => {
    userStorage.getRoles(
      user,
      (userWithRoles) => {
        alert(
          `Hello ${userWithRoles.name}, you have a ${userWithRoles.role} role`
        );
      },
      (error) => {
        console.log(error);
      }
    );
  },
  (error) => console.log(error)
);
반응형
728x90

10. JSON 개념 정리 와 활용방법 및 유용한 사이트 공유 JavaScript JSON | 프론트엔드 개발자 입문편 (JavaScript ES6)

// JSON
// JavaScript Object Notation

// 1. Object to JSON
// stringfy(obj)
let json = JSON.stringify(true);
console.log(json);

json = JSON.stringify(["apple", "banana"]);
console.log(json);

const rabbit = {
  name: "tori",
  color: "white",
  size: null,
  birthDate: new Date(),
  //   symbol: Symbol("id"), // Symbol은 JSON에 포함되지 않는다.
  jump: () => {
    console.log(`${this.name} can jump!`);
  },
};

json = JSON.stringify(rabbit);
console.log(json);

json = JSON.stringify(rabbit, ["name", "color", "size"]);
console.log(json);

console.clear();
json = JSON.stringify(rabbit, (key, value) => {
  console.log(`key: ${key}, value: ${value}`);
  //   return value;
  return key === "name" ? "ellie" : value;
});
console.log(json);

// 2. JSON to Object
// parse(json)
console.clear();
json = JSON.stringify(rabbit);
const obj = JSON.parse(json, (key, value) => {
  console.log(`key: ${key}, value: ${value}`);
  //   return value;
  return key === "birthDate" ? new Date(value) : value; // string을 다시 object로..
});
console.log(obj);
rabbit.jump();
// obj.jump(); // JSON으로 변환될때 함수는 포함되지 않는다.

console.log(rabbit.birthDate.getDate());
console.log(obj.birthDate.getDate()); // JSON으로 넘어가면서 string이 되었기 때문에, parse를 이용해 다시 object로 넘어와도 여전히 string이다.
반응형

+ Recent posts