Promise all

νƒœν˜„Β·2021λ…„ 4μ›” 29일
0
post-thumbnail

πŸ™‹πŸ»β€β™‚οΈ"λ¦¬μ•‘νŠΈ ν”„λ‘œμ νŠΈλ₯Ό μ§„ν–‰ν•˜λ‹€κ°€ 톡신을 ν•  λ•Œ 반볡적으둜 νŒ¨μΉ­μ„ ν•  λ•Œκ°€ μžˆμŠ΅λ‹ˆλ‹€."

μ’€ 더 효율적인 방법이 μ—†μ„κΉŒ κ³ λ €ν•˜λ‹€κ°€ JS의 Primise.all을 톡해 반볡된 μ½”λ“œμ˜ 양을 μ€„μ΄λŠ” 방법을 μ‚¬μš©ν•΄ λ³΄μ•˜μ–΄μš”.

특히, μ‹€μ œ ν”„λ‘œμ νŠΈμ—μ„œ Promise의 async 와 await λ₯Ό λ‚¨μš©ν•˜μ—¬ 병λͺ©ν˜„상이 생길 수 μžˆλ‹€κ³ ν•˜μ—¬ λ‚΄κ°€ μž‘μ„±ν•œ μ½”λ“œλ„ κ°œμ„ μ΄ ν•„μš”ν•˜λ‹€λŠ” 것을 λŠκΌˆμŠ΅λ‹ˆλ‹€.

ν•˜λ£¨λ™μ•ˆ κ³΅λΆ€ν•œ λ‚΄μš©μ„ ν† λŒ€λ‘œ κ°„λ‹¨νžˆ μ„€λͺ…ν•˜κ² μŠ΅λ‹ˆλ‹€.

Promise.all?


Primise.all() λ©”μ†Œλ“œλŠ” 순회 κ°€λŠ₯ν•œ 객체에 주어진 λͺ¨λ“  ν”„λ‘œλ―ΈμŠ€κ°€ μ΄ν–‰λœ ν›„, ν˜Ήμ€ ν”„λ‘œλ―ΈμŠ€κ°€ 주어지지 μ•Šμ•˜μ„ λ•Œ μ΄ν–‰ν•˜λŠ” Primiseλ₯Ό λ°˜ν™˜ν•œλ‹€.

주어진 ν”„λ‘œλ―ΈμŠ€ 쀑 ν•˜λ‚˜κ°€ κ±°λΆ€ν•˜κ±°λ‚˜, 첫 번째둜 κ±°μ ˆν•œ ν”„λ‘œλ―ΈμŠ€μ˜ 이유λ₯Ό μ‚¬μš©ν•΄ μžμ‹ λ„ κ±°λΆ€ν•œλ‹€.

Promise.all(μžμ„Έν•œ μ„€λͺ…)


Promise.all은 νŒŒλΌλ―Έν„°λ‘œ 배열을 λ°›λŠ”λ‹€. λ”°λΌμ„œ λͺ¨λ“  μš”μ†Œκ°€ ν”„λ‘œλ―ΈμŠ€ κ°μ²΄μ΄κ±°λ‚˜ ν”„λ‘œλ―ΈμŠ€ 객체가 ν¬ν•¨λœ 배열을 인자둜 λ„£μ–΄μ€€λ‹€.

PromiseλŠ” 말 κ·ΈλŒ€λ‘œ ν•˜λ‚˜λΌλ„ κ±°λΆ€λ˜λ©΄ Promise.all 은 μ¦‰μ‹œ κ±°λΆ€λœλ‹€.

κ²°κ΅­, Promise All은


Promise μ•ˆμ— μžˆλŠ” APIλ₯Ό ν™œμš©ν•˜λŠ” 방식이닀. Promise 배열을 μ „λ‹¬ν•˜κ²Œ 되면 λͺ¨λ“  Promise듀이 λ³‘λ ¬μ μœΌλ‘œ μ²˜λ¦¬κ°€ λ˜μ„œ ν•œκΊΌλ²ˆμ— λͺ¨μ•„μ£ΌλŠ” 역할을 ν•œλ‹€.

1. Promise all() μ‹œλ„λŠ” ν–ˆμ§€λ§Œ 잘 μ§„ν–‰λ˜μ§€ μ•Šμ•˜μŒ

const urls = [
      'http://localhost:3000/data/productListData1.json',
      'http://localhost:3000/data/productListData2.json',
      'http://localhost:3000/data/productListData3.json',
    ];
    const requests = urls.map(url => fetch(url));
    Promise.all(requests)
      .then(responses => Promise.all(responses.map(res => res.json())))
      .then(res =>
        res.forEach(res => {
          this.setState({ cardList: this.state.cardList.concat([res]) });
        })
      );

2. Promise all을 μ μš©ν–ˆμ§€λ§Œ 이제 stateλ₯Ό μ–΄λ–»κ²Œ 관리할 지

componentDidMount() {
    const urls = [
      'http://localhost:3000/data/productListData1.json',
      'http://localhost:3000/data/productListData2.json',
      'http://localhost:3000/data/productListData3.json',
    ];
    const requests = urls.map(url => fetch(url));
    Promise.all(requests)
      .then(responses => Promise.all(responses.map(res => res.json())))
      .then(response =>
        this.setState({
          cardList: response[0],
          cardList1: response[1],
          cardList2: response[2],
        })
      );
  }

κΌΌκΌΌν•œ μ—λŸ¬μ²˜λ¦¬κ°€ ν•„μš”ν•œ Promise all


Promise.all() 을 μ“°λŠ” 것은 μ’‹μ§€λ§Œ, λ°°μ—΄ 쀑 ν•˜λ‚˜λΌλ„ μ—λŸ¬κ°€ λ°œμƒν•˜λ©΄ 전체가 κ±°λΆ€λ˜κΈ° λ•Œλ¬Έμ— 꼼꼼히 μ‚΄νŽ΄λ΄μ•Ό ν•œλ‹€.

profile
μ•ˆλ…•ν•˜μ„Έμš”, 지식을 κ³΅μœ ν•˜λŠ” κ³΅κ°„μž…λ‹ˆλ‹€.

0개의 λŒ“κΈ€