HTML & CSS & JS/JS

[JS] promise.all 과 promise.race

가자미 2021. 3. 17. 20:11

promise.all : 여러 개의 프로미스 인스턴스를 받아 모두 완료될 때까지 기다리고 모든 반환값을 반환

promise.race : 여러 개의 프로미스 인스턴스 중 가장 먼저 끝날 때까지 기다리고 가장 먼저 끝난 반환 값을 반환

//promise.all & promise.race
const getDog = async ()=>{
    await sleep(1000);
    return 'bark!';
}
const getCat = async ()=>{
    await sleep(1000);
    return 'meow!';
}
async function process2(){
    const results=await Promise.all([getDog(), getCat()]);
    //promise배열을 받아 모두 끝나면 동시에 결과를 배열로 반환하는 await promise.all()
    console.log(results);//값을 배열로 받지 않고 따로 받고 싶으면 비구조화
    const results2= await Promise.race([getDog(), getCat()]);
    //promise배열을 받아 이 중 가장 빨리 끝난 값만 반환
}