[ javascript ] promise 를 async & await 로 쉽게 써보자 > javascript&jQuery

본문 바로가기

사이트 내 전체검색

javascript&jQuery

[ javascript ] promise 를 async & await 로 쉽게 써보자

작성일 21-02-27 23:44

페이지 정보

작성자 웹지기 조회 3,276회 댓글 0건

본문

promise 를 async & await 로 쉽게 써보자 

//promise는 chaning가 가능하다.

//체인이 많아 지면 복잡해진다.

//async await 동기식으로 순서를 작성하는 것 처럼 간편하게 작성가능

//기존에 존재하는 promise 위에 간단한 api를 제공하는데

//더 간편하게 제공하는 것을 syntactic sugar 

//프로토 타입을 베이스트로한 살짝 덭붙여진 것


//async & await

//clear style of using promise :)



//1. async(비동기)

function fetchUser() {

    //do network request in 10 secs....

    //return 'test';

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

        //do network request in 10 secs....


        resolve('test');

    })

}

const user = fetchUser();

user.then(console.log);

console.log(user);


//이러한 promise를 async를 통해서 바로 실행이 가능하다.

//syntactic sugar

async function fetchUser2() {

    return 'test2';

}

const user2 = fetchUser2();

user2.then(console.log);

console.log(user2);


//2. await

function delay(ms) {

    //promise를 리턴하는데, 

    //정해진 ms(밀리세컨드)가 지나면 resolve를 호출하는 promise를 리턴하게 된다.

    return new Promise(resolve => setTimeout(resolve, ms));

}


async function getApple() {

    //await는 async 함수가 붙은 곳에서만 사용이 가능

    await delay(1000);

    //에러처리를 

    return 'apple';

}


async function getBanana() {

    await delay(1000);

    return 'banana';

}


/*

 * promise로 사용하는 함수를 만들어보자면

 * 이런식의 체이닝으로 구성이 가능하다.

function getBanana() {

    return delay(1000)

    .then(()=> 'banana');

}

*/



function pickFruits(){

    //이런식으로 promise도 중첩적으로 너무 체인닝을 하게 되면

    //콜백지옥이 되는건 마찬가지이다.

    return getApple()

    .then(apple =>{

        return getBanana()

        .then(banana => `${apple}+${banana}`);

    });

}

pickFruits().then(console.log);


//이녀석을 async를 통해서 간단하게 해줄 수 가 있다.

async function pickFruits2() {

    const apple = await getApple();

    const banana = await getBanana();

    return `${apple} + ${banana}`;

}

pickFruits2().then(console.log);



/*

 * 에러처리

async function getApple3() {

    await delay(1000);

    throw 'error';

    return 'apple3';

}

*/

async function getApple3() {

    await delay(1000);

    return 'apple3';

}


async function getBanana3() {

    await delay(1000);

    return 'banana3';

}


async function pickFruits3() {

    //여기서 사과와 바나나를 불러오는데 

    //사과에서 1초대기, 바나나에서 또 1초대기를 하게 된다.

    //이렇게 순차로 진행되면 비효율 적이다.

    //const apple = await getApple3();

    //const banana = await getBanana3();

    //이렇게 하면 1초만에 병렬적으로 두개를 실행하는게 가능해 진다.

    //이렇게 getApple3과 getBanana3이 서로 다른것을 불러올때는

    //서로의 관계가 없으므로 다른 방법으로 불러온다.

    //promise에서 제공하는 all이라는 api를 사용하면 된다.


    const applePromise3 = getApple3();

    const bananaPromise3 = getBanana3();

    const apple3 = await applePromise3;

    const banana3 = await bananaPromise3;


    return `${apple3} + ${banana3}`;

}

pickFruits3().then(console.log);


//3. useful Promise APIs 

function pickAllFruits() {

    return Promise.all([getApple3(), getBanana3()])

    .then(fruits => fruits.join('+++'));

}

pickAllFruits().then(console.log);


//먼저출력되는 값중 하나를 출력하는 함수

function pickOnlyOne() {

    return Promise.race([getApple3(), getBanana3()]);

}

pickOnlyOne().then(console.log);


추천0

비추천 0

댓글목록

등록된 댓글이 없습니다.

전체 63건 1 페이지

이미지 목록

게시물 검색
Copyright © 즐거운 코딩 생활 ( funyphp ). All rights reserved.
PC 버전으로 보기