How to call async function over an array of elements synchronously in such a way that the next async function should be called only after the completion of async call over the current element.
for instance if we look at the following piece of code.
const fetch = require("cross-fetch");
function wait(a) {
fetch(`https://jsonplaceholder.typicode.com/todos/${a}`)
.then(response => response.json())
.then(json => console.log(json));
}
const data = [1, 2, 3, 5, 6, 7, 8, 9, 10];
async function test() {
for (const ele of data) {
await wait(ele);
}
}
test();
whenever I am executing the above piece of code it is logging responses randomly but not synchronously according to the array. i.e
{"userId":1,"id":8,"title":"quo adipisci enim quam ut ab","completed":true}
{"userId":1,"id":9,"title":"molestiae perspiciatis ipsa","completed":false}
{"userId":1,"id":10,"title":"illo est ratione doloremque quia maiores aut","completed":true}
{"userId":1,"id":7,"title":"illo expedita consequatur quia in","completed":false}
{"userId":1,"id":1,"title":"delectus aut autem","completed":false}
{"userId":1,"id":6,"title":"qui ullam ratione quibusdam voluptatem quia omnis","completed":false}
{"userId":1,"id":3,"title":"fugiat veniam minus","completed":false}
{"userId":1,"id":5,"title":"laboriosam mollitia et enim quasi adipisci quia provident illum","completed":false}
{"userId":1,"id":2,"title":"quis ut nam facilis et officia qui","completed":false}
Here you can clearly see that the responses are not in order. Is there any way that these function can be called synchronously but only after completing the current call.
for await .. of