I have a situation where I need to loop through an array of URLs and fetch the result, but I need to preserve the order of requests, that is the first request should be "saved" (write to a file) first, and so on. The result from the requests are text files and their content do not have any data that reveals the original URL or order.
I have made a demo below, which fetches dummy JSON data.
let promises = [];
let data = [];
let i = 1;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
const fn = async() => {
while (i < 5) {
promises.push(
fetch('https://reqres.in/api/users/' + i, {
mode: 'cors',
headers: headers
})
.then(response => response.json())
.then(json => {
data.push(json)
})
)
i++;
}
await Promise.all(promises).then(() => {
console.log(data);
})
}
fn();
If you test the above code, you can see that the results are in random order (based on id), and since the files in my original code are text files, I can't sort it after fetch.
datain thePromise.all()code.