Answer the question
In order to leave comments, you need to log in
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
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 ... // Ждет завершения любого промиса
}
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 questionAsk a Question
731 491 924 answers to any question