K
K
kuzubina2020-11-04 12:11:18
Node.js
kuzubina, 2020-11-04 12:11:18

How to correctly implement an asynchronous loop in node.js?

How to properly implement an asynchronous loop?
There is a first request that receives a list of id and then it is necessary to go through all the ids one by one with a detailed request, and so that the next iteration starts only after a detailed request is received and some action (for example, writing it to a file)
there is a function of this type

axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(async function (response) {

  const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

  for await (const item of items) {
    const res = await axios.get(`https://jsonplaceholder.typicode.com/users/${item}`)

    fs.writeFileSync('test.json', JSON.stringify(res.data.phone, null, 2));

  }

  console.log(response.data);
  
})
.catch(function (error) {
  console.log(error);
})

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex, 2020-11-04
@kuzubina

Use await in a regular loop. In this case, all iterations will be sequential.

const items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

  for (const item of items) {
    const res = await axios.get(`https://jsonplaceholder.typicode.com/users/${item}`) // Ждет заверения запроса

    await fs.promises.writeFile('test.json', JSON.stringify(res.data.phone, null, 2)); // Ждет завершения записи
   
   await ... // Ждет завершения любого промиса
  }

D
Dmitry, 2020-11-04
@dimoff66

If without blocking await, then something like this

const promise = axios.get('https://jsonplaceholder.typicode.com/todos/1')
promise
.then(response => ({ response, items: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] }))
.then(nextThen)
.catch(console.log)

const nextThen = ({ response, items }) => {
  if (!items.length) {
    console.log(response)
    return
  }
  const [nextValue, ...rest] = items
  promise
    .then(item =>  axios.get(`https://jsonplaceholder.typicode.com/users/${item}`))  
    .then(res => {
      fs.writeFileSync('test.json', JSON.stringify(res.data.phone, null, 2))
      return ( { response, items: rest })
    })
    .then(nextThen)
  return nextValue
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question