자바스크립트 3. 데이터타입, data types, let vs var, hoisting | 프론트엔드 개발자 입문편 (JavaScript ES5+)
let name = 'ellie';
console.log(name);
name = 'hello';
console.log(name);
let
이라는 키워드를 통해서 변수를 지정하면, 저장공간 하나를 차지하는 포인터가 된다{ }
)를 사용하여 블럭 안에 내용을 작성하게 되면, 블럭 밖에서는 해당 내용을 사용할 수 없게 된다console.log
메서드를 사용하면 제대로 작동하지 않는다age = 4;
console.log(age);
var age;
var
키워드를 사용하여 변수를 선언하는 순간 스크립트 맨 위로 올린다var
대신 let
을 사용함이 지당하다!const daysInWeek = 7;
const maxNumber = 5;
Primitive Type(Single Item) : number, string, boolean, null, undefined, symbol
number
const count = 17; // integer
const size = 17.1; // decimal number
const infinity = 1 / 0;
const negativeInfinity = -1 / 0;
const nAn = 'not a number' / 2;
string
const char = 'c';
const brendan = 'brendan';
const greeting = 'hello' + brendan;
const helloBob = `hi ${brendan}!`;
)을 사용하여 일일이 스페이스와 따옴표를 넣지 않고도 한 번에 작성할 수 있다. 달러사인(${ }
)을 사용하여 변수를 넣어줄 수 있다boolean
const canRead = true;
const test = 3 < 1; // false
null
let nothing = null;
undefined
let x = undefined;
let x;
// 둘 다 undefined임
symbol
const symbol1 = Symbol('id')
const symbol2 = Symbol('id')
console.log(symbol1 === symbol2);
Object Type(Box Container)
const ellie = {name:'ellie', age:20}
Function(First-Class Function)
let text = 'hello' //**string 'hello'**
text = 1; // string -> **number 1**
text = '7' + 5; // string + number -> **string '75'**
text = '8' / '2' // string(number) / string(number) -> **number 4**
자바스크립트 4. 코딩의 기본 operator, if, for loop 코드리뷰 팁 | 프론트엔드 개발자 입문편 (JavaScript ES6)
console.log('my' + 'cat');
console.log('1' + 2);
console.log(`string literals: 1 + 2 = $
+
) 기호를 사용해서 문자, 문자열과 숫자를 더해서 문자열로 만드는 기능
) 기호와 달러사인(${ }
)을 활용하여 다양한 특수문자와 변수를 문자열로 한꺼번에 써주는 것이 가능하다console.log(1+1) // add 덧셈
console.log(1-1) // substract 뺄셈
console.log(1/1) // divide 나눗셈
console.log(1*1) // multiply 곱셈
console.log(5%2) // remainder 나머지
console.log(2**3) // exponentiation 제곱
let counter = 2;
const preIncrement = ++counter;
// counter = counter + 1; **3**
// preIncrement = counter; **3**
const postIncrement = counter++;
// postIncrement = counter; **3**
// counter = counter + 1; **4**
=
)를 사용하는 것으로 변수에 값을 할당(저장)하는 것을 의미한다let x = 3;
let y = 6;
≤, ≥, <, >
)를 사용한다console.log(10 < 6);
console.log(10 > 6);
console.log(10 <= 6);
console.log(10 >= 6);
||
) 는 하나라도 참이라면 참을 리턴하며, 모두 거짓이어야 거짓을 리턴한다&&
)는 모두 참이어야 참을 리턴하며, 하나라도 거짓이면 거짓을 리턴한다!
)는 값을 반대로 변경한다const value1 = true;
const value2 = 4 < 2;
// || (or) finds the first truthy value
console.log(`or: ${value1 || value2 || check()}`);
// && (and) finds the first falsy value
console.log(`and: ${value1 && value2 && check()}`);
function check() {
for (let i=0; i<10; i++) {
console.log('^~^');
}
return true;
}
// ! (not)
console.log(!value1);
==
)로 검사해 같은지, (!=
)를 사용해 다른지 검사한다===
)로 검사해 같은지, (!==
)를 사용해 다른지 검사한다const stringFive = '5';
const nubmerFive = 5;
// == loose eqality, with type conversion
console.log(stringFive == numberFive);
console.log(stringFive != numberFive);
// === strict eqality, no type conversion
console.log(stringFive === numberFive);
console.log(stringFive !== numberFive);
console.log(0 == false); // true
console.log(0 === false); // false
console.log('' == false); // true
console.log('' === false); // false
console.log(null == undefined); // true
console.log(null === undefined); // false<<<
===
를 사용해 검사하면 false가 나오게 된다const ellie1 = {name: 'ellie'};
const ellie2 = {name: 'ellie'};
const ellie3 = ellie1;
console.log(ellie1 == ellie2); // false
console.log(ellie1 === ellie2); // false
console.log(ellie1 === ellie3); // true
const name = 'ellie';
if (name === 'ellie') {
console.log('Welcome, Ellie!);
} else if (name === 'coder') {
console.log('You are amazing coder');
} else {
console.log('unknown');
}
condition ? value1 : value2;
형식으로 사용한다console.log(name === 'ellie' ? 'yes' : 'no');
const browser = 'IE';
switch (browser) {
case 'IE':
console.log('go away!');
break;
case 'IE':
console.log('go away!');
break;
case 'Chrome':
console.log('love you!');
break;
case 'Firefox':
console.log('love you!');
break;
default:
console.log('same all!');
break;
}
while
let i = 3;
while (i > 0) {
console.log(`while: ${i}`);
i--;
}
do-while
do {
console.log(`do while: ${i}`);
i--;
} while (i > 0);
for-loop
for(시작; 조건; 단계;)
의 방식으로 반복문을 설계함for (i=3; i>0; i--) {
console.log(`for: ${i}`);
}
nested-loop
for (let i=0; i<10; i++) {
for (let j=0; j<10; j++) {
console.log(`i: ${i}, j: ${j}`);
}
}
break, continue
for (let i=0; i<10; i++) {
if (i%2 === 0) {
continue;
};
console.log(i);
}
for (let j=0; j<10; j++) {
console.log(j);
if (j===8) {
break
}
}
자바스크립트 5. Arrow Function은 무엇인가? 함수의 선언과 표현 | 프론트엔드 개발자 입문편(JavaScript ES6)
function 함수이름(파라미터1, 파라미터2..) { 내용.. 리턴; }
과 같은 방식을 사용한다함수이름()
형식으로 함수를 호출할 수 있다function printLog(message) {
console.log(message)
}
log('Hello@');
function changeName(obj) {
obj.name ='coder';
}
const ellie = {name: 'ellie'};
changeName(ellie);
console.log(ellie);
파라미터=’디폴트값’
으로 초기화를 해두면 값이 없을 때, 이 디폴트 값을 사용function 불고기버거(주문, 소스='불고기소스'){
console.log('오더 들어왔어요', 주문, 소스);
}
불고기버거('1개', '케첩');
…args
형태로 파라미터를 작성한다function 조립_햄버거(...속재료){
console.log("참깨빵 위에");
for (i=0; i<속재료.length; i++) {
// i = 0일때,
console.log(속재료[i]);
}
console.log("따란딴딴딴!"):
}
조립_햄버거('순쇠고기 패티 두 장', '특별한 소스', '양상추', '치즈', '피클', '양파까지')
밖에서는 안이 보이지 않고, 안에서만 밖을 볼 수 있다. - 드림코딩 엘리
자식 이기는 부모 없다 - 김태인
- Block Level Scope : 중괄호(
{ }
)를 사용하여 만든 블럭 내부에 있는 변수- Global Level Scope: 블럭 외부에 있는 변수
let globalMessage = 'global';
function printMessage() {
let message = 'hello'; // local variable
console.log(message);
console.log(globalMessage);
function printAnother() {
console.log(message);
let childMessage = 'babo';
console.log(childMessage);
}
printAnother()
}
printMessage()
function sum(num1, num2) {
return num1 + num2
}
let result = sum(1,2);
function 공룡등장(내일배움캠퍼) {
if (내일배움캠퍼 == "입실체크완료") {
return "잘했어요^^";
}
console.log("저를 화나게 하지 마세요!");
}
let 황영상 = "입실체크완료";
공룡등장(황영상);
변수이름()
의 형태로만 호출이 가능하다 → Anonymous Functionconst print = function(){console.log('프린트');} // anonymous function
const print = function print_sentences(){console.log('프린트');} // named function
print();
const print_again = print;
print_again();
// 우리끼리 적어본 식
const source_sum = [1,2]
const result_sum = function(source_sum){return source_sum[0] + source_sum[1]}
const result_sul = (source_sum) => source_sum[0] + source_sum[1]
function 쓰레기(고철, 버리자, 버리지말자){
if (고철 === '깡통'){
버리자();
} else {
버리지말자();
}
}
const 버리자 = function () {
console.log('갖다버려 그냥 쓰레기야')
};
const 버리지말자 = function () {
console.log('버리지말자 쓰레기 아닌거같애')
};
쓰레기('깡통', 버리자, 버리지말자)
변수 = (parameter) ⇒ return;
형식으로 Arrow Function을 사용한다// 블럭은 열고 리턴은 없는 버전
const 버스카드찍기 = (age) => {
if (age > 20){console.log("감사합니다");}
else {console.log("안녕하세요");}
}
버스카드찍기(21);
// 블럭을 안열고 리턴이 있는 버전
const 입실체크 = (했니) => console.log(했니);
const 했니 = "했어";
입실체크(했니);
// 블럭을 열고 내용과 리턴이 있는 버전
const 복약관리 = (질병) => {
let 약;
if (질병 == "피로") {약="피로회복제";}
else if (질병 == "고혈압") {약="혈압약";}
else {약="당신은 건강하시네요!"}
return 약
}
console.log(복약관리("고혈압"));
const simple = () => console.log('simplesimple');
simple()
const 나머지 = (a, b) => {
return a % b;
};
나머지(10,3)
const mix =()=>리턴 값;
// 정답을 보고 썻네.......
const add = (a, b) => a + b;
const calculator = (command, num1, num2) => {
switch(command) {
case 'add':
return num1 + num2;
case 'substract':
return num1 - num2;
case 'multifly':
return num1 * num2;
case 'divide':
return num1 / num2;
case 'remainder':
return num1 % num2;
default:
throw Error('unkown command')
}
}
caculator("add", 1,2);
(function hello(){console.log('IIFE');})();
자바스크립트 6. 클래스와 오브젝트의 차이점(class vs object), 객체지향 언어 클래스 정리 | 프론트엔드 개발자 입문편 (JavaScript ES6)
- 클래스는 붕어빵틀이다
- 클래스는 여러 번 재사용 가능하게 하는 템플릿과 같은 역할을 수행한다
- 클래스는 단 한 번 선언하면 된다
- 클래스 자체에는 데이터가 들어있지 않다
- 클래스를 이용해서 데이터를 넣은 것을 오브젝트라고 한다
- 클래스는 메모리에 들어가지 않지만, 인스턴스로 생성한 오브젝트는 데이터 메모리에 할당된다
- 붕어빵 틀에 내용물을 넣고 만들어낸 붕어빵이 오브젝트에 해당한다
키워드 , 이름, 생성자, 필드, 메서드를 선언
하여 작성한다class 클래스{
생성자(필드1, 필드2){
this.필드1 = 필드1;
this.필드2 = 필드2;
}
메서드(){
메서드 내용
}
}
변수 = new 클래스(필드)
를 사용하여 선언한다// class declaration
class Person {
// 생성자
constructor(name, age) {
// 필드
this.name= name;
this.age= age;
}
// 메서드
speak() {
console.log(`${this.name}: hello!`);
}
}class Person {
// 생성자
constructor(name, age) {
// 필드
this.name= name;
this.age= age;
}
// 메서드
speak() {
console.log(`${this.name}: hello!`);
}
}
const ellie = new Person('ellie', 20);
console.log(ellie.name);
console.log(ellie.age);
ellie.speak();
class Person {
constructor(firstName, lastName) {
this.firstName= firstName;
this.lastName = lastName;
this.age= age;
}
get age() {
return this._age;
}
set age(value) {
this._age = value < 0 ? 0 : value;
}
}
const user1 = new User('Steve', 'Job', -1);
console.log(user1.age);
#privateField
처럼 해시태그를 사용해서 내부에서만 쓰거나 변경할 수 있도록 작성할 수 있음class Experiment {
publicField = 2;
#privateField = 0;
}
class Article {
static publisher = 'Dram Coding';
constructor(articleNumber) {
this.articleNumber = articleNumber;
}
static printPublisher() {
console.log(Article.publisher);
}
}
const article1 = new Article(1);
const article2 = new Article(2);
console.log(Article.publisher);
Article.printPublisher();
class MarvelCinematicUniverse {
constructor(name, hero, villian) {
this.name = name;
this.hero = hero;
this.villian = villian;
}
명대사() {
console.log(`이 영화에서 명대사를 말한 인물은 ${this.villian}입니다!`)
}
}
class Ironman extends MarvelCinematicUniverse {}
class Spiderman extends MarvelCinematicUniverse {}
const rdj = new Ironman('ironman2', '토니 스타크', '울트론');
rdj.명대사()
const 토비맥과이어 = new Spiderman('spiderman3', '피터 파커', '그린 고블린');
class Shape {
constructor(width, height, color) {
this.width = width;
this.height = height;
this.color = color;
}
draw() {
console.log(`drawing ${this.color} color of`);
}
getArea() {
return width * this.height;
}
// 사각형이라는 클래스에 쉐이프 클래스 상속
class Rectangle extends Shape {}
class Triangle extends Shape {
draw() {
super.draw();
console.log('⚠')
}
getArea() {
return (this.width * this.height) / 2;
}
}
const rectangle = new Rectangle(20,20,'blue');
rectangle.draw();
console.log(rectangle.getArea());
const triangle = new Triangle(20,20,'red');
triangle.draw();
console.log(triangle.getArea());
extends 부모클래스
라고 추가로 작성하는 것으로, 부모클래스를 자식클래스가 상속하게 된다Overriding
super.메서드()
를 사용하여 둘 다 사용할 수 있다인스턴스 instanceof 클래스
형태로 사용한다console.log(rectangle instanceof Rectangle); // true
console.log(triangle instanceof Rectangle); // false
console.log(triangle instanceof Triangle); // true
console.log(triangle instanceof Shape); // true
console.log(triangle instanceof Object); // true
자바스크립트 7. 오브젝트 넌 뭐니? | 프론트엔드 개발자 입문편 (JavaScript ES6)
object literal
const obj = { };
과 같이 중괄호를 열어서 만들기const ellie = {name:'ellie', age:4}; // {key : value}
ellie.hasJob = true; // 오브젝트 선언 이 후의 밸류 생성
delete ellie.hasJob; // 오브젝트 선언 이 후의 밸류 삭제
object constructor
const obj = new Object();
와 같이 new를 사용해서 만들기변수.프로퍼티
혹은 변수[’프로퍼티’]
스트링
형식으로 프로퍼티에 접근할 수있다. 후자의 경우 Computed Property에 해당된다.
) 을사용하여 작성하지만, 정확하게 밸류의 타입을 몰라서 메서드를 작성하지 못 할 때는 대괄호([ ]
) 방식의 컴퓨트 프로퍼티로 작성한다코딩할 때는 점 하나 찍는게 편하니까! 또, 메서드를 자연스럽게 뒤에 붙여서 작성하기 좋다!
반면 컴퓨트 프로퍼티의 경우, 값이 무엇이든 상관없거나 값이 뭐가 들어올 지 아예 모르는 경우, 단순 검사식에 사용하거나 할 때는 적어주기도 한다
function printValue(obj, key) {
// console.log(obj.key); 를 이 경우에는 사용할 수 없다
console.log(obj[key]);
}
printValue(ellie, 'name');
printValue(ellie, 'age');
// 일반적인 오브젝트의 선언방법
const person1 = {name: 'bob', age: 2};
const person2 = {name: 'steve', age: 3};
const person3 = {name: 'dave', age: 4};
// Shorthand
const person4 = makePerson('ellie', 30);
console.log(person4);
function makePerson(name, age) {
return {
name,
age,
};
}
function 대문자로 시작하는 함수이름 (필드){}
와 같은 방식으로 선언하며, 이 함수자체가 constructor 역할을 수행한다고 하여 constructor function 이라고 부른다const person4 = makePerson('ellie', 30);
console.log(person4);
function Person(name, age) {
// this = {};
this.name = name;
this.age = age;
// return this;
}
key in object
형식으로 작성한다console.log('name' in ellie);
for (key in obj)
for (key in object) {}
형식으로 사용함for (key in ellie) {
console.log(key);
}
for (value of iterable)
for (value of array) {}
형식으로 사용함const array = [1,2,3,4];
for (value of array) {
console.log(value);
}
Object.assign
을 사용하여 오브젝트를 클로닝하는 것이 가능하다const user4 = Object.assign({}, user);
const fruit1 = {color: 'blue'};
const fruit2 = {color: 'red', size:'big'};
// 두 개를 합침
const fruit3 = {size:'small'};
const mixed = Object.assign({}, fruit1, fruit2, fruit3); // **red small**
//뒤에 있는 프로퍼티가 덮어 씌움
자바스크립트 8. 배열 제대로 알고 쓰자. 자바스크립트 배열 개념과 APIs 총정리 | 프론트엔드 개발자 입문편 (JavaScript ES6 )
new Array();
를 사용하거나 대괄호([]
) 안에 데이터를 넣어 선언할 수 있다.const arr1 = new Array();
const arr2 = [1,2];
배열[배열.length-1]
로 찾을 수 있다const emoji = ['👩🚀', '🐳'];
console.log(emoji);
console.log(emoji.length);
console.log(emoji[0]);
for (let i=0; i<emoji.length; i++) {
console.log(emoji[i]);
}
for (let target_emoji of emoji) {
console.log(target_emoji);
}
emoji.forEach(function (변수, 인덱스, 배열){
console.log(emoji, index);
})
emoji.forEach((emoji, index, array) => console.log(emoji, index))
배열.forEach()
라는 형식으로 작성하게 된다변수, 인덱스, 배열
을 파라미터로 받는다Push
emoji.push('🙋♂️', '🐢');
console.log(emoji);
Pop
emoji.pop();
unshift
emoji.unshift('🙋♂️','🐢');
shift
emoji.shift();
splice(start: number, deleteCount?: number)
형식으로 작성한다emoji.push('🧩','🎯','😈');
console.log(emoji);
emoji.splice(1, 3); // 1번째 인덱스의 아이템부터 3개의 아이템을 순서대로 삭제하기
emoji.splice(1); // 1번째 인덱스의 아이템부터 지움(즉, 뒤는 모두 지움)
emoji.splice(1, 1, '💾','🎨'); // 1번째 인덱스의 아이템을 1개 지우고 뒤의 아이템을 1번째 인덱스 자리부터 추가
const emoji2 = ['💡','📜'];
const newEmoji = emoji.concat(emoji2);
배열.indexOf(값)
형식으로 사용한다console.log(emoji);
console.log(emoji.indexOf('🐳');
console.log(emoji.includes('👩🚀');
console.log(emoji.includes('🧛♂️');
console.log(emoji.indexOf('🧛♂️');
자바스크립트 9. 유용한 10가지 배열 함수들. Array APIs 총정리 | 프론트엔드 개발자 입문편 ( JavaScript ES6)
배열.join(’구분자’);
형식으로 작성한다const fruits = ['apple', 'banana', 'orange'];
const result = fruits.join(',');
console.log(result);
문자열.split(’구분자’)
를 사용하여 작성한다const fruits = '🍎, 🥝, 🍌, 🍒';
const result = fruits.split(',');
console.log(result);
배열.reverse();
const array = [1, 2, 3, 4, 5];
const result = array.reverse();
console.log(result);
console.log(array);
배열.slice(시작인덱스, 마지막인덱스+1)
형식으로 작성한다const array = [1, 2, 3, 4, 5];
const result = array.slice(2, 5);
console.log(result);
console.log(array);
배열.find(콜백함수(파라미터)){내용, 리턴}
형식을 사용하며, 콜백함수를 만들어서 전달해야함 → Arrow Function 이 가능하다// 준비코드
class Student {
constructor(name, age, enrolled, score) {
this.name = name;
this.age = age;
this.enrolled = enrolled;
this.score = score;
}
}
const students = [
new Student('A', 29, true, 45),
new Student('B', 28, false, 80),
new Student('C', 30, true, 90),
new Student('D', 40, false, 66),
new Student('E', 18, true, 88),
];
const result = students.find((student) => student.score === 90);
console.log(result);
배열.filter(콜백함수(파라미터){내용 리턴})
형식으로 작성한다const result = students.filter((student) => student.enrolled);
console.log(result);
배열.map(콜백함수(파라미터){내용 리턴}
형식으로 작성하게 된다const result = students.map((student) => student.score);
console.log(result);
배열.some(콜백함수(파라미터) {내용, 리턴}
형식으로 작성한다const result = students.some((student) => student.score < 50);
console.log(result);
const result2 = !students.every((student) => student.score >= 50);
console.log(result2);
배열.every(콜백함수(파라미터) {내용, 리턴})
형식으로 작성한다배열.reduce((이전값,지금값) {비교, 리턴(이전값으로 돌아감)}
형식으로 작성한다const result = students.reduce((prev, curr) => prev + curr.score, 0);
console.log(result / students.length);
const result = students
.map((student) => student.score)
.filter((score) => score >= 50)
.join();
console.log(result);
.sort((a,b) ⇒ a-b)
형식으로 작성한다(오름차순, 내림차순은 b-a)const result = students
.map((student) => student.score)
.sort((a, b) => b - a)
.join();
console.log(result);
자바스크립트 10. JSON 개념 정리 와 활용방법 및 유용한 사이트 공유 JavaScript JSON | 프론트엔드 개발자 입문편 (JavaScript ES6)
key:value
파일 포맷 형식으로 작성한다JSON.
이라는 메서드를 기본으로 사용한다stringify
stringify
메서드는 JSON.
메서드의 내부 함수이며 오브젝트를 받아서 string으로 변환해주는 기능을 수행한다json = JSON.stringify(['apple', 'banana']);
console.log(json);
const rabbit = {
name: 'tori',
color: 'white',
size: null,
birthDate: new Date(),
jump: () => {
console.log(`${name} can jump!`);
}
};
json = JSON.stringify(rabbit);
console.log(json);
- 위와 같은 오브젝트에서 JSON으로 시리얼라이즈를 진행할 때 몇 가지의 예외사항이 있다
- JSON의 공통형식에 포함되지 않는 Javascript의 독자적인 형태인 symbol과 같은 자료형은 포함되지 않는다
- 함수는 참조하고 있는 것이 데이터가 아닌 레퍼런스이므로 JSON에 포함되지 않는다
- JSON에서 하나만 보내주고 싶은 밸류가 존재한다면 `JSON.stringify(오브젝트, [키값], [키값] ..)`의 형식으로 적는 것으로 원하는 프로퍼티만 보내주는 것도 가능하다
- JSON에서 조금 더 세밀하게 사용하는 방법으로 콜백함수를 사용하는 방법이 있다
- 아래와 같이 코드를 작성하면, 오브젝트부터 불러오기 시작해서 각 필드 값을 출력한다
```jsx
json = JSON.stringify(오브젝트, (key, value) => {
console.log(`key : ${key}, value: ${value}`);
return key === 'name' ? 'ellie' : value;
}
console.log(json);
```
JSON.parse(JSON데이터)
메서드를 사용해서 데이터를 변환해주기만 하면 된다!const json = JSON.stringify(rabbit)
const data = JSON.parse(json)
parse(JSON데이터, (키, 밸류) {내용 리턴})
형식으로 작성한다obj = JSON.parse(json, (key, value) => {
console.log(`key : ${key}, value: ${value}`);
return key === 'birthDate' ? new Date(value) : value;
}
console.log(rabbit.birthDate.getDate();
console.log(obj.birthDate.getDate();
Best JSON Viewer and JSON Beautifier Online
JSON Parser Online to parse JSON
자바스크립트 11. 비동기 처리의 시작 콜백 이해하기, 콜백 지옥 체험 😱 JavaScript Callback | 프론트엔드 개발자 입문편 (JavaScript ES6)
// synchronous. 코드 전체를 읽어 순서대로 실행됨
console.log(1);
console.log(2);
console.log(3);
setTimeout
메서드를 작성하여 코드를 1초 뒤에 실행하게 된다면, 그것은 즉시 실행하는 동기적 특성과는 다르다.// asynchronous. 코드 전체를 읽었지만 특정 코드가 순서대로 실행되지는 않았다
console.log(1);
setTimeout(()=>console.log(2),1000);
console.log(3);
Synchronous Callback
function printImmediately(print){
console.log('즉시 호출하는 동기 콜백');
print();
}
printImmediately(print() => console.log('hello'));
Asynchronous Callback
function printWithDelay(print, timeout) {
console.log('호출을 막는 비동기 콜백');
setTimeout(print, timeout);
}
printWithDelay(setTimeout() => console.log('async callback'), 200);
필요한게 1번함수 선언, 2번함수 선언, console.log, 시간제한, 호출
Q. 에어컨을 작동하는 프로그램을 작성해보기
- 전원을 넣어 에어컨을 켬
- 콜백 함수로 에어컨 온도를 조절함
// 콜백 함수. 일반 버전
let power = false;
let temp = 22;
function 온오프(power, callback){
if (power === false){
power=true;
console.log('전원이 켜졌습니다');
callback(temp);
}
else if (power === true) {
power=false;
console.log('전원이 꺼졌습니다');
}
else { console.log('잘못된 입력값입니다');}
return power;
}
function 온도조절(temp){
let now_temp = temp;
console.log(`현재 에어컨 온도는 ${now_temp}입니다`);
}
power = 온오프(power, 온도조절);
// 콜백 함수. 애로우 펑션 버전
let power = false;
let temp = 22;
function 온오프(power, callback){
if (power === false){
power=true;
console.log('전원이 켜졌습니다');
callback(temp);
}
else if (power === true) {
power=false;
console.log('전원이 꺼졌습니다');
}
else { console.log('잘못된 입력값입니다');}
return power;
}
power = 온오프(power, (temp)=> {
let now_temp = temp;
console.log(`현재 에어컨 온도는 ${now_temp}입니다`);
});
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 passrod');
userStorage.loginUser(
id,
password,
user => {
userStorage.getRoles(
user,
userWithRole => {
alert(
`Hello ${userWithRole.name}, you have a ${userWithRole.role} role`
);
},
error => {
console.log(error);
}
);
},
error => {
console.log(error);
}
);
자바스크립트 12. 프로미스 개념부터 활용까지 JavaScript Promise | 프론트엔드 개발자 입문편 (JavaScript ES6)
new Promise((resolve, reject) => {})
형태로 생성이 가능하다const promise = new <Promise((resolve, reject) => {
// doing some heavy work (network, read files)
console.log('doing something...');
setTimeout(() => {
resolve('ellie');
// reject(new Error('no network'));
}, 2000);
});
resolve()
메서드 사용해서 네트워크에서 받아온, 파일을 읽어온 데이터를 바탕으로 값을 적어 전달한다reject(new Error(’error message’));
메서드를 사용해서 네트워크 통신이 실패했다는 것을 오류를 담아 전달한다then, catch, finally
메서드를 사용한다// then 메서드. 성공 케이스 핸들링
prmoise //
.then(value => {
console.log(value);
});
.catch(error => {
console.log(error);
});
.finally(() => {
console.log('finally');
});
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);
});
})
자바스크립트 13. 비동기의 꽃 JavaScript async 와 await 그리고 유용한 Promise APIs | 프론트엔드 개발자 입문편 (JavaScript ES6)
async function fetchUser() {
return 'ellie';
}
const user = fetchUser();
user.then(console.log);
console.log(user);
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function getApple() {
await delay(2000);
return '🍎';
}
getApple();
async function getBanana() {
await delay(1000);
return '🍌';
}
getApple() ;
이라는 구문이 실행되기 위해서는 2초라는 시간을 들이고, 리턴 사과를 한 다음에 비로소 구문이 정상적으로 작동된다.async function pickFruits() {
const apple = await getApple();
const banana = await getBanana();
return `${apple} + ${banana}`;
}
async function pickFruits() {
const applePromise = getApple();
const bananaPromise = getBanana();
const apple = await applePromise;
const banana = await bananaPromise;
return `${apple} + ${banana}`;
}
function pickAllFruits() {
return Promise.all([getApple(), getBanana()]).then(fruits => fruits.join(' + ')
);
}
pickAllFruits().then(console.log);
Promise.all()
을 이용해 함수 모두를 리턴해줄 하나의 프로미스로 작성한다.then
메서드로 리턴한 값을 활용하게 되는데,getApple()
, getBanana()
의 리턴 값을 가져와서join(’ + ‘)
메서드로 사과 + 바나나 로 붙여줘서 리턴한다Promise.race([getApple(),getBanana()])
를 이용하면 리스트 내에 제일 먼저 받는 값만 리턴해줄 수 있다
function pickOnlyOne() {
return Promise.race([getApple(), getBanana()]);
}
pickOnlyOne().then(console.log);