개발 일지 (TIL)

TIL 2023 08 21

늘곰's 2023. 8. 21. 22:42

오늘 배운 것

  • 콜백함수
  • 알고리즘 문제풀이

콜백함수란 

호출시점에 대해 제어권을 가짐

setInterval 함수는 반복해서 매개변수로 받은 콜백함수의 로직을 수행

var count = 0;

var time = setInterval(function(){
    console.log(count);
    if(++count>4)clearInterval(time);
},1000)

인자에 대한 제어권을 가짐

map 함수

// 인덱스나 커런트 밸류는 사람이 이해하는 것
// 컴퓨터가 인식하는것은 자리에 있는 수
//인덱스와 커런트밸류 위치를 바꾸면 10 0 20 1 30 2 [5,6,7] 이나옴
var newArr = [10,20,30].map(function(currentValue,index){
    console.log(currentValue,index)
    return currentValue + 5;
});

//결과는 뭐가 될까?
console.log(newArr)
Array.prototype.map123 = function(callback,thisArg){
    //함수에서 리턴할 결과 배열
    var mappedArr = [];

    for(var i=0; i < this.length; i++){
        var mappedValue =callback.call(thisArg || global, this[i]);
            mappedArr[i] = mappedValue;     
    }
    
    return mappedArr;
};

var newArr = [1,2,3].map123(function(number){
    return number * 2;
});

console.log(newArr);

콜백지옥

// 콜백지옥이란
// 매개변수에 익명함수가 계속 반복될때 들여쓰기가 많아지며
// 그것이 많아지면 질수록 지금은 작동 할 수도 있지만 
// 코드의 가독성이 극히 나빠지고 추후 유지보수 할 때 지옥이 펼쳐짐 
// 비동기적인 작업 수행 할 때 발생

//동기적 sync 예시
// 주문한 커피가 나올때까지 기다려주세요 !


// 비 동기적 async예시
// 주문한 후에 진동벨이 울리면 커피를 가지러 오세요!
// setTimeout(function(){
//     console.log('여기가 1번째 입니다. 근데 setTime아웃을 걸었어요')
// },1000);

// console.log('여기가 두번째입니다.')
// 요청,실행 대기, 보류 등과 관련된 코드는 모두 비동기

// 비동기작업
// 순서를 보장하지 않음

// 비동기 작업의 동기적 표현
// Promise
//처리가 끝나면 알려달라는 약속
//new 연산자로 넘어감
// resolve 성공 reject 실패
// then 다음 catch 오류로 추적 가능

new Promise((resolve) => {
    setTimeout(function(){
        let name = '에스프레소';
        console.log(name);
        resolve(name);
    },500);
})
.then((prevName) =>{
    //이 안에서 새로운 Promise 를 만듬
    return new Promise((resolve) => {
        setTimeout(function(){
            let name = prevName + ', 아메리카노';
            console.log(name);
            resolve(name);
        },500)

    })
})
.then((prevName) =>{
    //이 안에서 새로운 Promise 를 만듬
    return new Promise((resolve) => {
        setTimeout(function(){
            let name = prevName + ', 카페모카';
            console.log(name);
            resolve(name);
        },500)

    })
})
.then((prevName) =>{
    //이 안에서 새로운 Promise 를 만듬
    return new Promise((resolve) => {
        setTimeout(function(){
            let name = prevName + ', 카페라떼';
            console.log(name);
            resolve(name);
        },500)

    })
})

리팩토링

// refacttoring
// re: 다시
// factoring 

var addCoffee = function (name) {
    return function (prevName) {
        //이 안에서 새로운 Promise 를 만듬
        return new Promise(function (resolve) {
            setTimeout(function () {
                //백틱
                let newName = prevName ? `${prevName}, ${name}` : name;
                console.log(newName);
                resolve(newName);
            }, 500);

        });
    };
};

addCoffee('에스프레소')()
.then(addCoffee(', 아메리카노'))
.then(addCoffee(', 카페모카'))
.then(addCoffee(', 카페라떼'))

제너레이터 함수 선언

//iterable 반복될수 있는 /할수있는
// yield 양보하다 미루다


// 1  제너레이터 함수 안에서 쓸 addCoffee 함수 선언
var addCoffee = function (prevName, name){
    setTimeout(() =>{
        coffeeMaker.next(prevName ?`${prevName}, ${name}` : name);
    },500) 
         
};
// 2 제너레이터 함수 선언
// 함수 뒤에 *안붙으면 오류남
// function* 함수
// 제너레이터 함수를 정의할 때 사용되는 키워드
// 이걸 안쓰면 오류가 남
// yield 가 들어있으면 제너레이터 함수이고 function* 로 함수선언
var coffeeGenerator = function* (){
    var espresso = yield addCoffee('','에스프레소');
    console.log(espresso); 
    var americano = yield addCoffee('','아메리카노');
    console.log(americano); 
    var mocha = yield addCoffee('','카페모카');
    console.log(mocha); 
    var latte = yield addCoffee('','카페라떼');
    console.log(latte); 

};

var coffeeMaker = coffeeGenerator();
coffeeMaker.next()

await 

// Promise
// 이전에 썻던 방법 : then(그러면~~)
// 이번에 쓸 방법  : async(비동기) / await(기다리다)

// coffeeMaker 함수에서 호출할 함수 , addCoffee 선언
// Promise 반환
var addCoffee = function (name) {
    return new Promise((resolve) => {
        setTimeout(function(){
            resolve(name);
        },500);
    });
};
// 화살표 함수라면 소괄호 앞에 async 
//
var coffeeMaker = async function() {
    var coffeList = '';
    var _addCoffee = async function (name) {
        coffeList +=(coffeList ? ',':'') + (await addCoffee(name));
    };
// Promise 를 반환하는 함수인 경우
// , await 를 만나면 무조건 끝날때 까지 기다린다
await _addCoffee('에스프레소');
console.log(coffeList);
await _addCoffee('아메리카노');
console.log(coffeList);
await _addCoffee('카페모카');
console.log(coffeList);
await _addCoffee('카페라떼');
console.log(coffeList);

};

coffeeMaker();