*Generator

: 함수의 실행을 중간에 멈췄다가 재개할 수 있는 기능

function* fn() {
  console.log(1);
  yield 1;
  console.log(2);
  yield 2;
  console.log(3);
  console.log(4);
  yield 3;
  return "finish";
} catch (e) {
  console.log(e);
}

const a = fn();

 

next(), return(), throw()

 

iterable

 -Symbol.iterator 메서드가 있다.

 -Symbol.iterator 는 iterator를 반환해야 한다.

 

iterator

 -next 메서드를 가진다.

 -next 메서드는 value와 done속성을 가진 객체를 반환한다.

 -작업이 끝나면 done은 true가 된다.

 

 

 

 

 

 

 

 

반응형
async function getName() {
  //return Promise.resolve("Tom");
  throw new Error("err...");
}

getName().catch((err) => {
  console.log(err);
});

 

//await : async함수 내부에서만 사용가능

function getName(name) {
  return new Promise ((resolve, reject) => {
    setTimeout(() => {
      resolve(name);
    }, 1000);
  });
}

async function showName(){
  const result = await getName('Mike');
  console.log(result);
}

console.log("시작");
showName();

 

const f1 = () => {
  return new Promise((res, rej)=> {
    setTimeout(() => {
      res("1번 주문 완료");
    }, 1000);
  });
};

const f2 = (message) => {
  console.log(message);
  return new Promise((res, rej)=> {
    setTimeout(() => {
      res("2번 주문 완료");
    }, 3000);
  });
};

const f3 = (message) => {
  console.log(message);
  return new Promise((res, rej)=> {
    setTimeout(() => {
      res("3번 주문 완료");
    }, 2000);
  });
};

async function order(){
  const result1 = await f1();
  const result2 = await f2(result1);
  const result3 = await f3(result2);
  console.log(result3);
  console.log("종료");
}
order();

→ Promise/then 보다 async/await 를 썼을 때 가독성이 좋다. 

 

const f1 = () => {
  return new Promise((res, rej)=> {
    setTimeout(() => {
      res("1번 주문 완료");
    }, 1000);
  });
};

const f2 = (message) => {
  console.log(message);
  return new Promise((res, rej)=> {
    setTimeout(() => {
      //res("2번 주문 완료");
      rej(new Error("err.."));
    }, 3000);
  });
};

const f3 = (message) => {
  console.log(message);
  return new Promise((res, rej)=> {
    setTimeout(() => {
      res("3번 주문 완료");
    }, 2000);
  });
};

console.log("시작");
async function order() {
  try{
    const result1 = await f1();
    const result2 = await f2(result1);
    const result3 = await f3(result2);
    console.log(result3);
  } catch (e) {
    console.log(e);
  }
  console.log("종료");
}
order();
반응형

const pr = new Promise((resolvereject) => {           
(resolve: 성공했을 때 실행되는 함수, reject: 실패했을 때 실행되는 함수)
  //code    
});

어떤 일이 완료된 이후 실행되는 함수: callback 함수

 

<new Promise>                                                      

state: pending(대기)                      

result: undefined                                                             

          ↓

resolve(value)                   ☞                    state: fulfilled(이행됨)

                                                                   result: value (resolve로 전달받은 값)

 

reject(error)                  ☞                    state: rejected(거부됨)

                                                              result: error

 

ex)

const pr = new Promise((resolve, reject) => {
  setTimeout(()=>{
    resolve('OK')
  }, 3000)
});

 state: pending(대기)                    ☞                  state: fulfilled(이행됨)

 result: undefined                        (3s)                 result: 'OK'

 

 

const pr = new Promise((resolve, reject) => {
  setTimeout(()=>{
    reject(new Error('error..'))
  }, 3000)
});

 state: pending(대기)                    ☞                  state: rejected(거부됨)

 result: undefined                        (3s)                 result: error

 

→판매자의 코드: 주문을 받으면 3초 후에 성공인지 실패인지 알려줌.

 

소비자의 코드(then):

pr.then(       
    function(result){},    //이행되었을 때 실행, result = 'OK'
    function(err){}     //거부되었을 때 실행, err = 에러값
)
const pr = new Promise((resolve, reject) => {
  setTimeout(()=>{
    resolve('OK')
  }, 3000)
});

pr.then(
    function(result){
      console.log(result + '가지러 가자.');     //"OK가지러 가자."
    },
    function(err){
      console.log('다시 주문해주세요..');
    }
);

거부되었을 때 = catch함수로 대체 가능

pr.then(                                                    pr.then(

     function(result){},              →                   function(result){}

     function(err){}                                     ).catch(

);                                                                    function(err){}

                                                                )

 

finally = 이행되었든, 거부되었든 실행 

pr.then(
    function(result){}
).catch(
    function(err){}
).finally(
    function(){
      console.log('--- 주문 끝 ---')
    }
)

 

const pr = new Promise((resolve, reject)=> {
  setTimeout(()=> {
    resolve("OK");
  }, 1000);
});

console.log("시작");
pr.then((result) => {
  console.log(result);
})
  .catch((err) => {
  console.log(err);
})
  .finally(() => {
  console.log("끝");
});

 

*Callback Hell

const f1 = (callback) => {
  setTimeout(function () {
    console.log("1번 주문 완료");
    callback();
  }, 1000);
};

const f2 = (callback) => {
  setTimeout(function () {
    console.log("2번 주문 완료");
    callback();
  }, 3000);
};

const f3 = (callback) => {
  setTimeout(function () {
    console.log("3번 주문 완료");
    callback();
  }, 2000);
};

console.log('시작')
f1(function(){
  f2(function(){
    f3(function(){
      console.log("끝");
    });
  });
});

 

*Promise Chain

const f1 = () => {
  return new Promise((res, rej)=> {
    setTimeout(() => {
      res("1번 주문 완료");
    }, 1000);
  });
};

const f2 = (message) => {
  console.log(message);
  return new Promise((res, rej)=> {
    setTimeout(() => {
      res("2번 주문 완료");
    }, 3000);
  });
};

const f3 = (message) => {
  console.log(message);
  return new Promise((res, rej)=> {
    setTimeout(() => {
      res("3번 주문 완료");
    }, 2000);
  });
};

console.log('시작');
f1()
.then((res) => f2(res))
.then((res) => f3(res))
.then((res) => console.log(res))
.catch(console.log)
.finally(() => {
  console.log("끝");
});

 

const f1 = () => {
  return new Promise((res, rej)=> {
    setTimeout(() => {
      res("1번 주문 완료");
    }, 1000);
  });
};

const f2 = (message) => {
  console.log(message);
  return new Promise((res, rej)=> {
    setTimeout(() => {
      rej("xxx");
    }, 3000);
  });
};

const f3 = (message) => {
  console.log(message);
  return new Promise((res, rej)=> {
    setTimeout(() => {
      res("3번 주문 완료");
    }, 2000);
  });
};

//Promise.all
console.time("x")
Promise.all([f1(), f2(), f3()]).then((res) => {
  console.log(res);
  console.timeEnd("x");
});


//Promise.race : 하나라도 완료되면 종료
console.time("x")
Promise.race([f1(), f2(), f3()]).then((res) => {
  console.log(res);
  console.timeEnd("x");
});


console.log("시작");
f1()
  .then((res) => f2(res))
  .then((res) => f3(res))
  .then((res) => console.log(res))
  .catch(console.log)
  .finally(() => {
    console.log("시작");
});

 

 

반응형
//생성자 함수
const User = function (name, age){
  this.name = name;
  this.age = age;
  //this.showName = function() {
  //  console.log(this.name);
  //};
};
User.prototype.showName = function (){
  console.log(this.name);
};



const mike = new User("Mike", 30);

class User2 {
  constructor(name, age) {     //constructor: 객체를 만들어주는 생성자 메소드
    this.name = name;
    this.age = age;
  }
  showName(){      //클래스 내에 정의된 메소드는 User2의 프로토타입에 저장된다.
    console.log(this.name);
  }
}

const tom = new User2("Tom", 19);

 

*Class: 상속

//extends 

class Car {
  constructor(color){
    this.color = color;
    this.wheels = 4;
  }
  drive() {
    console.log("drive..");
  }
  stop() {
    console.log("STOP!");
  }
}

class Bmw extends Car{
  park(){
    console.log("PARK");
  }
}

const z4 = new Bmw("blue");

 

*Class: 메소드 오버라이딩(method overriding)

class Car {
  constructor(color){
    this.color = color;
    this.wheels = 4;
  }
  drive() {
    console.log("drive..");
  }
  stop() {
    console.log("STOP!");
  }
}

class Bmw extends Car{
  park(){
    console.log("PARK");
  }
  stop(){
    super.stop();          //super.메소드명을 사용하여 부모 클래스에 정의된 메소드들을 사용할 수 있다.
    console.log("OFF")
  }
}

const z4 = new Bmw("blue");
반응형
const car = {
  wheels : 4,
  drive() {
    console.log("drive..");
  },
};

const bmw = {
  color : "red",
  navigation : 1,
};

const benz = {
  color : "black",
};

const audi = {
  color : "blue",
};

bmw.__proto__ = car;   //bmw는 car에 상속

const x5 = {
  color : "white",
  name : "x5",
};

x5.__proto__ = bmw;  //x5는 bmw에 상속 
                    //Prototype Chain

▶ for ...in 을 이용해서 객체의 프로퍼티 순환하기

   for (p in x5){

       console.log(p);

   }

   x5 : {color: "white", name: "x5"}

   Object.keys(x5);  → ["color", "name"]

   Object.values(x5);  →  ["white" , "x5"] 

     →name과 color를 제외한 프로퍼티는 프로토타입에서 정의한 프로퍼티들이다.

 

▶ for(p in x5){

       if(x5.hasOwnProperty(p)) {

             console.log('o' , p);

       } else {

             console.log('x', p);

       }

}  → color , name

→ hasOwnProperty를 사용하면 객체가 직접 가지고 있는 프로퍼티만 반환해준다.

 

 

//생성자 함수 이용
const car = {
  wheels = 4;
  drive() {
    console.log("drive..");
  },
};


const Bmw = function(color) {
  this.color = color;
};

const x5 = new Bmw("red");
const z4 = new Bmw("blue");

x5.__proto__ = car;
z4.__proto__ = car;

  ↓ 더 간편히 바꾸기

//생성자 함수 이용


const Bmw = function(color) {
  this.color = color;
};

Bmw.prototype.wheels = 4;
Bmw.prototype.drive = function() {
  console.log("drive..");
};

const x5 = new Bmw("red");
const z4 = new Bmw("blue");

  

 

반응형

*call, apply, bind:

 함수 호출 방식과 관계없이 this 를 지정할 수 있음.

 

 

1. call

  call메서드는 모든 함수에서 사용할 수 있으며, 

   this를 특정값으로 지정할 수 있다. 

const mike = {
  name : "Mike",
};


const tom = {
  name : "Tom",
};

function showThisName() {
  console.log(this.name);
}

showThisName();    //this = window
showThisName.call(mike);   //this = mike
const mike = {
  name : "Mike",
};


const tom = {
  name : "Tom",
};

function showThisName() {
  console.log(this.name);
}

function update(birthYear, occupation) {
  this.birthYear = birthYear;
  this.occupation = occupation;
}
  
update.call(mike, 1999, "singer");         //this = mike
console.log(mike);

 

 

 

2. apply

 apply는 함수 매개변수를 처리하는 방법을 제외하면 call과 완전히 같다.

 call은 일반적인 함수와 마찬가지로 매개변수를 직접 받지만, apply는 매개변수를 배열로 받는다. 

 

const nums = [3, 10, 1, 6, 4];

//나머지 매개변수 사용할 때
const minNum = Math.min(...nums);
const maxNum = Math.max(...nums);

//apply 사용할 때
const minNum = Math.min.apply(null, nums);
// = Math.min.apply(null, [3, 10, 1, 6, 4]) ->null은 this값인데, Math.min이나 Math.max는 this가 필요없어 아무 숫자나 넣은 것

const maxNum = Math.max.call(null, ...nums);  ->call은 매개변수를 순서대로 직접 받음.
// = Math.max.call(null, 3, 10, 1, 6, 4)


console.log(minNum);
console.log(maxNum);

 

 

 

3. bind

 함수의 this값을 영구적으로 바꿀 수 있다. 

 

const mike = {
  name : "Mike",
};

function update(birthYear, occupation) {
  this.birthYear = birthYear;
  this.occupation = occupation;
}

const updateMike = update.bind(mike);

updateMike(1980, "police");
console.log(mike);

 

const user = {
  name : "Mike",
  showName : function () {
    console.log(`hello, ${this.name}`);
  },
};

user.showName();   //"hello, Mike"
 
let fn = user.showName;

fn.call(user);     //"hello, Mike"
fn.apply(user);     //"hello, Mike"


let boundFn = fn.bind(user);

boundFn();     //"hello, Mike"
반응형

*setTimeout : 일정 시간이 지난 후 함수를 실행 

*setInterval : 일정 시간 간격으로 함수를 반복 

 

function fn(){
  console.log(3)
}
setTimeout(fn, 3000);  //fn: 일정시간 지난 후 실행되는 함수
                       // 3000 = 3s

setTimeout(function(){
    console.log(3)
}, 3000);                                = 위 함수와 똑같은 내용 

 

//함수에 인수가 존재할 때
function showName(name){
  console.log(name);
}

setTimout(showName, 3000, 'Mike');  //→Mike는 name의 첫번째 인수로 전달
      //   함수     시간    인수

 

 

clerTimeout은 예정된 작업을 없앰.

function showName(name){
  console.log(name);
}

cosnt tId = setTimout(showName, 3000, 'Mike');
clearTimeout(tId);

  → setTimeout은 timeId를 생성하는데, clearTimeout을 사용하면 3초가 지나기 전에 이 코드가 실행되므로 아무일도 일어나지 않는다.

 

 

-----------------------------------------------------------------------------------------------------

function showName(name){
  console.log(name);
}

 const tId = setInterval(showName, 3000, 'Mike');
 clearInterval(tId);   //반복실행 중간에 중지

 

delay= 0 으로 설정해도 기본 브라우저가 4s 딜레이가 있으므로 바로 실행되지 않는다. 

 

//setInterval, clearInterval

let num = 0;

function showTime() {
  console.log(`안녕하세요. 접속하신지 ${num++}초가 지났습니다.`);
  if(num > 5){             //5초간 실행하고 종료
    clearInterval(tId);
  }
}
const tId = setInterval(showTime, 1000);

 

반응형

*js는 '어휘적 환경(Lexical Environment)' 을 갖는다.

let one;    //→  undefined
one = 1;    //→  1

function addOne(num){       //addOne: function
  console.log(one + num);
}

addOne(5);

    → Lexical 환경: one- 초기화X (사용 불가) / addOne- function 초기화O (사용 가능)

     [내부 Lexical 환경]          →          [전역 Lexical 환경]        

      num : 5                        참조             one : 1

                                                              addOne : function

    내부   → 외부   → 전역 Lexical 환경 순으로 찾는다.

function makeAdder(x){      //1.<전역 Lexical환경>  
  return function(y){       //makeAdder : function 
    return x + y;           //add3 : (초기화x) -> function 
  } 
}
const add3 = makeAdder(3);   //2.<makeAdder Lexical환경> x:3
console.log(add3(2));   //5   //<익명함수 Lexical환경> y:2

const add10 = makeAdder(10);
console.log(add10(5));    //15
console.log(add3(1));    //4    → add10이 생성되도 add3은 똑같이 존재. 다른 환경이기 때문

→  function(y) : y를 가지고 있고 상위함수인 makeAdder의 x에 접근 가능 

     add3 함수가 생성된 이후에도 상위함수인 makeAdder의 x에 접근 가능

Colsure:

     함수와 Lexical 환경의 조합

     함수가 생성될 당시의 외부 변수를 기억

     생성 이후에도 계속 접근 가능 

     내부함수가 외부함수에 접근 가능 

 

function makeCounter() {
  let num = 0;        //외부함수
  
  return function () {
    return num++;             //내부함수
  };
}
let counter = makeCounter();

console.log(counter());  //0
console.log(counter());  //1
console.log(counter());  //2

 

 

   

    

 

 

   

    

반응형

+ Recent posts