Maison > interface Web > js tutoriel > le corps du texte

Le dilemme Promise.all() : quand ça aide et quand ça fait mal

Susan Sarandon
Libérer: 2024-09-21 16:30:03
original
420 Les gens l'ont consulté

The Promise.all( ) Dilemma: When it helps and When it hurts

최신 JavaScript 개발에서는 비동기 작업을 처리하는 것이 일반적인 작업입니다. API 요청, 데이터베이스 쿼리, 파일 읽기 등 비동기 코드 작업은 거의 피할 수 없습니다. 개발자가 접하게 되는 일반적인 도구 중 하나는 Promise.all()입니다. 그러나 저를 포함한 많은 사람들은 Promise.all()이 우리의 특정 사용 사례에 가장 적합한 솔루션인지 제대로 이해하지 못한 채 Promise.all()을 사용하려고 시도하는 함정에 빠질 수 있습니다.

1. Promise.all() 유행에 편승하기

개발자로서 새로운 기능이나 도구를 접하고 이러한 기능이나 도구가 모든 곳에서 구현되어야 한다고 가정하기 쉽습니다. 저는 Promise.all()을 사용하여 이러한 상황에 처해 있었습니다. 여러 Promise를 병렬로 실행하고 계속하기 전에 모든 Promise가 완료될 때까지 기다리는 방법에 대해 읽은 후 이를 내 코드에 통합하고 싶었습니다. 꼭 필요한지 충분히 이해하지 못한 채 시류에 편승하여 가능한 모든 곳에 적용했습니다.

강력한 도구이기 때문에 단순한 대안보다 더 낫다고 가정하기 쉽습니다. 하지만 문맥을 고려하지 않고 맹목적으로 Promise.all()을 적용하는 것이 항상 가장 효율적이거나 읽기 쉬운 코드로 이어지는 것은 아니라는 것을 곧 깨닫게 되었습니다.

2. 비동기 자바스크립트의 기본

Promise.all()이 언제 유용한지 자세히 알아보기 전에 먼저 JavaScript에서 비동기 함수가 작동하는 방식을 살펴보겠습니다. 비동기 함수를 작성하고 wait를 사용하면 JavaScript를 사용하면 나머지 코드를 차단하지 않고도 해당 작업이 수행될 수 있습니다. 이는 하나의 작업을 시작하고 결과를 기다리는 동안 다른 작업으로 넘어갈 수 있음을 의미합니다.

그러나 조심하지 않으면 작업이 독립적으로 실행될 수 있는데도 작업이 불필요하게 서로 종속되게 될 수 있습니다. Promise.all()을 사용하여 이러한 상황에 처하게 되었는데, 모든 비동기 기능을 병렬로 실행하는 것이 항상 좋은 아이디어라고 생각했습니다.

예: 비동기 함수의 순차적 실행

const fetchData = async () => {
  const data1 = await getChart();   // Request #1
  const data2 = await getDetails(); // Request #2
};
Copier après la connexion

data1과 data2가 코드에서 차례로 가져오더라도 브라우저는 여전히 두 요청을 모두 비동기식으로 거의 동시에 시작합니다. 실제로 네트워크 탭을 확인했을 때 두 요청이 거의 동시에 시작되는 것을 확인했습니다. 이를 통해 JavaScript가 이미 작업을 병렬로 처리하고 있으며 Promise.all()이 반드시 필요한 것은 아니라는 사실을 깨달았습니다.

3. 언제 Promise.all()을 사용해야 합니까?

처음에는 어디에서나 Promise.all()을 사용하려고 성급하게 사용했음에도 불구하고 이것이 정말 빛을 발하는 상황이 있습니다. 앞으로 진행하기 전에 여러 비동기 작업이 완료될 때까지 기다려야 할 때 특히 유용합니다.

Promise.all()을 사용하는 이유는 무엇입니까?

  1. 모든 약속을 기다리는 중: 여러 비동기 작업의 결과가 서로 의존적이거나 진행하기 전에 모든 작업을 완료해야 하는 경우 Promise.all()이 이상적입니다.
  2. 오류 처리: Promise.all()은 빠르게 실패합니다. 즉, Promise가 실패하면 전체 작업이 거부됩니다. 이는 모든 것이 함께 성공하도록 하거나 아무것도 진행되지 않도록 하려는 경우에 유용할 수 있습니다.
  3. 결합된 결과: 모든 Promise의 결과가 동시에 필요한 경우(예: 사용자 데이터와 구매 내역 결합) Promise.all()이 완벽한 솔루션입니다.

예: Promise.all() 사용

const fetchData = async () => {
  const [data1, data2] = await Promise.all([getChart(), getDetails()]);
  console.log('Both requests completed'); // This runs only when both requests finish
};
Copier après la connexion

이 예에서 getChart()와 getDetails()는 모두 병렬로 실행되며, 함수는 두 가지가 모두 완료될 때까지 기다렸다가 앞으로 나아갑니다. Promise.all()은 두 요청이 서로 연관되어 있고 함께 완료되어야 하는 이와 같은 상황에 적합합니다.

4. 내 경우에는 왜 Promise.all()이 필요하지 않았나요?

Promise.all()을 몇 번 적용한 후, 이것이 항상 내 코드를 더 좋게 만드는 것은 아니라는 사실을 깨닫기 시작했습니다. 사실 저는 일을 너무 복잡하게 만들고 있었습니다. 두 개의 독립적인 API 요청(getChart() 및 getDetails())이 있었는데 각각 자체 로딩 스피너와 결과가 있었지만 불필요하게 묶었습니다.

Promise.all()을 사용하여 요청이 독립적이고 서로 의존하지 않는 경우에도 결과를 처리하기 전에 두 요청이 모두 완료될 때까지 기다리도록 코드를 강제했습니다. 이와 같은 경우 Promise.all()은 실질적인 이점 없이 복잡성만 추가합니다.

5. When Promise.all() Might Be Overkill

Sometimes, Promise.all() is overkill. If your async functions are independent, meaning one doesn’t rely on the other to complete, then there’s no need to bundle them together. They can run in parallel just fine without waiting on each other, and you can handle their results independently. This realization hit me when I saw that JavaScript already handles asynchronous tasks efficiently without needing to group everything together.

When to Avoid Promise.all()

  1. Independent Async Functions: If your requests don’t depend on each other, they can complete at different times, and you can handle their results separately. There’s no need to wait for all of them to finish together.
  2. Individual Loading States: In my case, I had individual loading spinners for each request, but I was unnecessarily holding everything up by waiting for both requests. It’s better to handle each request separately and update the UI as soon as each one finishes.

Example: Independent Requests Without Promise.all()

useEffect(() => {
  getChart();   // Trigger first async request
  getDetails(); // Trigger second async request
}, []);
Copier après la connexion

In this setup, both requests run in parallel without needing Promise.all(). You can show individual loading states and handle each result independently, which is exactly what I needed for my project.

6. Real-World Scenarios for Using or Avoiding Promise.all()

Let’s look at how these concepts apply to real-world scenarios.

Scenario 1: Fetching Related Data (Use Promise.all())

Imagine you’re building a dashboard where you need to show user information and user purchase history together. In this case, you’d want to wait for both pieces of information to load before rendering the UI. Here, Promise.all() is the right choice:

const fetchData = async () => {
  const [userInfo, purchaseHistory] = await Promise.all([
    fetchUserInfo(),
    fetchUserPurchaseHistory()
  ]);
  console.log('Both user info and purchase history loaded');
};
Copier après la connexion

Scenario 2: Independent API Calls (Avoid Promise.all())

Now, let’s say you’re fetching chart data and table data for a dashboard, and these two pieces of information are independent of each other. You might want to show a spinner for the chart and a separate one for the table. In this case, there’s no need to wait for both requests to complete together:

useEffect(() => {
  getChart();   // Fire chart request
  getDetails(); // Fire table request
}, []);
Copier après la connexion

Both requests are independent, and you handle each of them separately, updating the UI as soon as each one completes. Promise.all() isn’t necessary here.

Conclusion: Don’t Jump on the Bandwagon

Promise.all() is a powerful tool, but it’s not always the best solution. I jumped on the bandwagon initially, assuming that using it everywhere would make my code better. However, I quickly learned that in cases where async functions are independent and have their own loading states, Promise.all() can actually make things more complicated.

Key Takeaways:

  • Use Promise.all() when you need to wait for multiple promises to resolve before proceeding.
  • Avoid Promise.all() when async tasks are independent, and you can handle them individually without unnecessary waiting.

Ultimately, it’s important to understand when and why to use a feature like Promise.all() instead of just assuming it’s always beneficial. After stepping back and re-evaluating my use case, I found that sticking with independent async calls was the right approach.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Derniers articles par auteur
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!