Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
how to loop in asynchronic function

I am new in js and don't understand why my loop is not working.

(async () => {
  let arr = []

  while(ticket.stop != true) {
    let data = await fetch("https://front-test.beta.aviasales.ru/search")
    let commit =  await data.json() 
    let ticketsURL = "https://front-test.beta.aviasales.ru/tickets?" + Object.keys(commit) + "=" + Object.values(commit)
    let ticketFetch = await fetch(ticketsURL)
    let ticket = await ticketFetch.json()
    console.log(ticket)
    arr.push(ticket)
  }
})()
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Edit: your code is returning an array containing more than 346 items and what you're trying to do simply looping over and over again and calling them. Can you explain what you're trying to do with your code?

I don't know exactly what you're trying to do with your code but that should vary with your own use case however what you're trying to do is can be summarized in a async-call-inside-a-loop. Now one thing to remember is when you create a loop there are two main things to keep in mind,

  • loop variables and index
  • scope of the loop

The key take is that when you fire a function inside of a loop it gains its own context and therefore persists the value. However directly calling some asynchronous calls will fail. Therefore JavaScript offers you something that can resolve this and they are called Immediately Invoked Function Expression or IIFE in short. Which is exactly what you have done however you have wrapped the entire loop inside of it.

In a nutshell the IIFE gains its own context so every next IIFE that is created by the loop will work and resolve separately.

const length = array.length;

for(var i = 0; i < length; i++){
    (function(index) {
        const response = // some async call
    }(i));
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!