재귀함수, Promise, async await

이재영·2023년 3월 30일
0

HTML CSS JS

목록 보기
14/22
post-thumbnail

재귀함수 : 자기 자신을 호출하는 함수

function add(n){

    if(n< 5){
        add(n+1);
        console.log(n);
    }
}
add(0);
출력결과

피보나치 수열 재귀함수로 구현

function fibonacci(n){
    if(n<2) return n;
  
    return fibonacci(n-1) + fibonacci(n-2);
}

for( let i=0 ; i<20; i++){
    console.log(fibonacci(i));
}
출력결과

Promise 와 async await

promise는 비동기 처리를 가능해주는 객체이다.
function testPromise(num){
  	//전달하는 함수값에 
    // resolve, reject 두가지의 매개변수를 받는데
    // resolve() 함수는 처리가 완료면 반환
    // reject() 함수는 처리가 오류면 반환
    
    return new Promise(function(res,rej){

        try {
            if(num>10) rej("숫자큼");
         
            setTimeout(function(){
                res(num+1);
        
            },num*1000);
            
        } catch (error) {
            rej(error);
        }
    })
}

testPromise(10).then(function(date){
    console.log(date);
    //데이터를 가져오고 처리할 구문을 여기에 작성하면 된다.
    //데이터를 가지고 처리해야할 작업
    
    return testPromise(date)
    // reslove를 실행하면 then()메소드가 실행되고
    // reject를 실행하면 catch()메소드가 실행된다.
}).then(function(a){
    console.log(a);
}).catch(function(err)
	console.log(err);
})
출력결과

async await 구문


async function asyncFun(){

    try {
        let temp = await testPromise(10);

        // promise 객체 res나 rej가 처리될때까지 기다리고 아래를 처리함
        // await는 promise를 기다리고 resolve 값을 반환한다.
        // async await는 짝이다. 붙어다닌다.
      
        console.log(temp);
        temp = await testPromise(temp);
        console.log(temp);

    }
    catch(error){
        console.log(error);
    }
}
asyncFun();

async await 구문과 .then이랑 .catch를
같이써도 작업은 잘돌아가도 안좋은 버릇이라 절대 같이 사용하지말자.

profile
한걸음씩

0개의 댓글