Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

55
Views
How to stop async for loop that is already in call stack?

When user hits search button first time it works like it should and it takes approx 30sec to fetch all the data, so if the user decides to click the search button again with new search term it all gets messed up because the previous async loop is not done yet. Please help to find a solution to kill previous call stack and restart the process without continuing previous loop.

searchButton.addEventListener("click", (e) => {
e.preventDefault();
getPrice(data);
}

async function getPrice(data) {
  for (singleResult of data) {
      await fetchWeb(Title)
  }
}

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

Use a global click counter:

let calls = 0;
searchButton.addEventListener("click", (e) => {
  e.preventDefault();
  getPrice(data, ++calls);
}

async function getPrice(data, id) {
  for (singleResult of data) {
    if (id !== calls) break;
//  ^^^^^^^^^^^^^^^^^^^^^^^^
    await fetchWeb(Title)
  }
}

As soon as calls changes, the currently active loop will stop.

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs