I'm quite new to Javascript. I have an array of persons and I want to make an HTTP request for every person and associate the response with the respective person and spit it out. I tried doing:
async function queryData() {
var persons = ["Alice", "Jerry", "David", "Bob"];
var parentToAppendTo = document.getElementById("response");
parentToAppendTo.innerHTML = "<h5> Response: </h5>";
await Promise.all(persons.map(async (person) => {
postRequest("http://localhost:8000/pay", {
"pay": person,
})
.then(response => response.json())
.then((data) => {
parentToAppendTo.innerHTML +=
"<div>" + person + "</div>\
<div>" + data.success + "</div>";
})
}));
// Do something else after resolving all requests
}
function postRequest(url, data) {
const options = {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
}
return fetch(url, options);
}
This is producing different results in different runs. Suppose if the server returns {"success": true}
only for Bob and false for everyone else, it would say something like:
"Alice": false
"Jerry": false
"David": false
"Bob": false
or
"Alice": false
"Jerry": true
"David": false
"Bob": false
I have checked Closures and workaround with closures but still couldn't find a way to get around this.
I'm sure that there's no problem from the server-side. It's something about closures regarding data
in .then(data => {...});
that's bugging me!
Thanks for the help in advance!