๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ“’ JavaScript

์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์˜ Promise()๋กœ callback์ง€์˜ฅ ๋ฒ—์–ด๋‚˜๊ธฐ

by Tamii 2021. 2. 25.
๋ฐ˜์‘ํ˜•

๋™๊ธฐ์  ์‹คํ–‰ 

 : ์ฝ”๋“œ๊ฐ€ ์ˆœ์„œ์— ๋งž์ถฐ์„œ ์ž๋™์ ์œผ๋กœ ์‹คํ–‰๋จ

hoisting

 : var๋ณ€์ˆ˜, function declaration( ํ•จ์ˆ˜์„ ์–ธ)๋“ค์ด์ž๋™์ ์œผ๋กœ ์ œ์ผ ์œ„์— ์„ ์–ธ๋จ 

 

callback ํ•จ์ˆ˜

 : ๋‚ด๊ฐ€ ์ „๋‹ฌํ•ด ์ค€ ํ•จ์ˆ˜๋ฅผ ๋‚˜์ค‘์— ์‹คํ–‰ํ•ด์ค˜

 

* setTimeout( hadler , timeout) 

  - handler : callback ํ•จ์ˆ˜

  - timeout: ์ง€์ •๋œ ์‹œ๊ฐ„  ms ๋‹จ์œ„ (1์ดˆ 1000)

 

๋น„๋™๊ธฐ ์‹คํ–‰ (์‹ค์Šต)

 

js์—”์ง„์€ ์ฝ”๋“œ๋ฅผ ์ œ์ผ ์œ„์—์„œ๋ถ€ํ„ฐ ์•„๋ž˜๋กœ ์‹คํ–‰ 

console.log('1');
setTimeout(function(){
    console.log(2);
},1000)

console.log('3');

//ํ™”์‚ดํ‘œ ํ•จ์ˆ˜๋กœ ํ‘œํ˜„ ๊ฐ€๋Šฅ
console.log('1');
setTimeout(()=> console.log('2'),1000);

console.log('3');

1 -> setTimeout( ๋ธŒ๋ผ์šฐ์ € API) -> 3

๋ธŒ๋ผ์šฐ์ €์—๊ฒŒ ์š”์ฒญ -> "๋ธŒ๋ผ์šฐ์ €์•ผ ์ด๊ฑฐ ํ•ด์ค˜" -> 1์ดˆ ์ง€๋‚จ -> console.log(2)์ „๋‹ฌ

 

 

 

๋™๊ธฐ ํ•จ์ˆ˜ 

console.log('1');
setTimeout(() =>console.log(2),1000);

console.log('3');

function printImm(print) {
    print();
}

printImm( ()=> console.log('heelo'));

1 > 3 >  heelo >  2

 

 

๋น„๋™๊ธฐ ํ•จ์ˆ˜

console.log('1');
setTimeout(() =>console.log(2),1000);

console.log('3');

function printImm(print) {
    print();
}

printImm( ()=> console.log('heelo'));


function printWaa(print,timeout){
    setTimeout(print,timeout);
}
printWaa( ()=> console.log('async callback'),2000);

1   > 3 >  heelo > 2  > async acllback

 

 


์ฝœ๋ฐฑ์ง€์˜ฅ ๋งŒ๋“ค๊ณ  ํ•ด๊ฒฐํ•ด๋ณด๊ธฐ 

// 1) ์‚ฌ์šฉ์ž ํ™•์ธ 2)๊ถŒํ•œ ๋ถ€์—ฌ  

// ๋‹น์žฅ ์„œ๋ฒ„์™€ ์—ฐ๊ฒฐ์€ ์•ˆ๋˜๋‹ˆ ๋น„์Šท ํ•˜๊ฒŒ setTimeout์„ ์ด์šฉํ•˜์—ฌ ๋น„๋™๊ธฐ ์ฒ˜๋ฆฌ 
class UserStorage {

	// 1) id์™€ pw ๋ฅผ ๋น„๊ตํ•ด์„œ ์‚ฌ์šฉ์ž๊ฐ€ ๋งž๋Š”์ง€ ํ™•์ธ 
    loginUser( id,password,onSuccess,onError){
        setTimeout(()=>{
            if(
                (id==='tami' && password==='cool')||
                (id==='coder' && password==='academy')
            ){
                onSuccess(id);
            }else{
                onError(new Error('not found'));
            }
        },2000);
    }
	
    // 2) ์‚ฌ์šฉ์ž๊ฐ€ ๊ด€๋ฆฌ์ž์ธ์ง€ ํ™•์ธ ํ›„ ๊ถŒํ•œ ๋ถ€์—ฌ
    getRoles(user,onSuccess,onError){
        setTimeout(()=>{
            if(user==='tami'){
                onSuccess({name:'tami',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,
            userWithRole =>{
                alert(`hello ${userWithRole.name},you have ${userWithRole.role}`);
            },
            error=>{console.log(error);}
        );
    },

    error=>{console.log(error);
    }

);

๋ฌธ์ œ์ 

1) ๊ฐ€๋…์„ฑ์ด ๋–จ์–ด์ง

2) ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง ์ดํ•ด๊ฐ€ ์–ด๋ ค์›€ 

 

 


Promise ํ”„๋กœ๋ฏธ์Šค

์ถœ์ฒ˜https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise

JS์—๋” ์ œ๊ณตํ•˜๋Š” ๋น„๋™๊ธฐ๋ฅผ ๊ฐ„ํŽธํ•˜๊ฒŒ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•˜๋Š” object

callback์„ ์“ฐ์ง€ ์•Š๊ณ  

 

state

pending -> fullfilled or rejected

 - pending : promise๊ฐ€ ๋งŒ๋“ค์–ด์ ธ์„œ ์šฐ๋ฆฌ๊ฐ€ ์ง€์ •ํ•œ operation์ด ์ง„ํ–‰์ค‘์ผ ๋–„

- fullfilled : operation ์„ฑ๊ณต์ ์œผ๋กœ ์‹คํ–‰ 

- rejected file ์ฐพ์„์ˆ˜ ์—†๊ฑฐ๋‚˜ network ๋ฌธ์ œ๊ฐ€ ์ƒ๊ฒผ์„ ๋–„

 

producer (์ •๋ณด ์ œ๊ณต์ž) ์™€ consumer(์ •๋ณด ์†Œ๋น„์ž) ์˜ ์ฐจ์ด

 

 

ํŒŒ์ผ์„ ์ฝ์–ด์˜ค๊ณ  ๋„คํŠธ์›Œํฌ ํ†ต์‹ ์ด ์ง„ํ–‰๋˜๋Š” ๋™์•ˆ ์•„๋ฌด์ผ๋„ ํ•˜์ง€ ์•Š์„ ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์— ๋‹ค๋ฅธ์ผ๋„ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๋„๋ก ๋น„๋™๊ธฐ์ ์œผ๋กœ ์ฒ˜๋ฆฌ

 

promise๋Š” execute

const promise = new Promise((res,rej)=>{
    console.log('doging somctins');
});

promise๊ฐ€ ๋งŒ๋“ค์–ด ์ง€๋Š” ์ˆœ๊ฐ„ network ํ†ต์‹ ์ด ์‹œ์ž‘๋จ executor(์ฝœ๋ฐฑํ•จ์ˆ˜== (res,rej))!! 

์‚ฌ์šฉ์ž๊ฐ€ ์š”๊ตฌํ•˜์ง€ ์•Š๋Š” ๋„คํŠธ์›Œํฌ ํ†ต์‹ ์ด ์ผ์–ด๋‚˜์ง€ ์•Š๊ฒŒ ์กฐ์‹ฌ 

 

 

ใ„น

// Producer
//์„ฑ๊ณตํ–ˆ์„ ๋–„ resolve
//์‹คํŒจ ์‹œ reject
const promise = new Promise((resolve,reject)=>{
    console.log('doging somctins');
    setTimeout(()=>{
        // resolve('tami');
        reject(new Error('no network'));
    },2000)
});

//Cousumer  value==tami


//then ์„ฑ๊ณต์‹œ
// catch ์—๋Ÿฌ์‹œ
// finally ์„ฑ๊ณต์—ฌ๋ถ€์™€ ๊ด€๊ณ„ ์—†์ด 
promise
    .then((value)=>{
    console.log(value);
    })
    .catch(error=>{
        console.log(error);
    })
      .finally(()=>{
        console.log('finally');
    })

 

promise ์ฒด์ด๋‹

 

.then : ๊ฐ’ ์ „๋‹ฌ, promise ์ „๋‹ฌ ๋‘˜๋‹ค ๊ฐ€๋Šฅ 

๋น„๋™๊ธฐ ๋™์ž‘๋“ค์„ ๋ฌถ์–ด์„œ ์ง„ํ–‰ํ•˜๊ธฐ๋„ ๊ฐ€๋Šฅ 

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));

 

Promise() ๋ฅผ ํ™œ์šฉํ•˜์—ฌ ์ฝœ๋ฐฑ์ง€์˜ฅ ๋น ์ ธ๋‚˜๊ฐ€๊ธฐ

class UserStorage {
    loginUser( id,password){
        return new Promise((resolve, reject)=>{
            
            setTimeout(()=>{
                if(
                    (id==='tami' && password==='cool')||
                    (id==='coder' && password==='academy')
                ){
                    resolve(id);
                }else{
                    reject(new Error('not fonud'));
                }
            },1000);

        })
    }

    getRoles(user){
        return new Promise((resolve,reject)=>{

            setTimeout(()=>{
                if(user==='tami'){
                    resolve({name:'tami',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,
    user=>{
        userStorage.getRoles(
            user,
            userWithRole =>{
                alert(`hello ${userWithRole.name},you have ${userWithRole.role}`);
            },
            error=>{console.log(error);}
        );
    },

    error=>{console.log(error);
    }

);

Promise๋ฅผ ์‚ฌ์šฉํ•จ์œผ๋กœ์จ ํ•œ๋ˆˆ์— ํ™•์ธํ•  ์ˆ˜ ์žˆ์Œ 


// Promise ์‚ฌ์šฉ 
const userStorage = new UserStorage();
const id = prompt('enter your id');
const password = prompt('enter your password');


userStorage.loginUser(id,password)
.then(user => userStorage.getRoles(user))
.then(user=>alert(`hello ${user.name},you have ${user.role}`))
.catch(console.log);

 

 

 

์ฐธ๊ณ ํ•œ ์˜์ƒ

www.youtube.com/watch?v=s1vpVCrT8f4&list=PLv2d7VI9OotTVOL4QmPfvJWPJvkmv6h-2&index=11

๋Œ“๊ธ€