Case: I have a list of 20 items (clients) on a page where I want to grab some info via API about each item (client); that will end up sending 20 requests for each page load even if the item (client) is duplicated/repeated (item could repeat 20 a page; that's 20 request for the same item)
What I wanna achieve: 2 things:
- To Send only to uniques without repeating. DONE using
new Set()
- To iterate through all the items but wait (stop looping) (if a request was sent) till it resolves and returns the required data
clientPhone
.
What I achieved: It logs all in sequence but console.log(clientPhone)
works only in the request function getAllCients()
, not in others, even though I assigned it to global variable.
What I did:
<script>
async function getAllClients (clientName, clientCode){
console.log("fired!")
await $.get("/api/clients", data => {
console.log(data)
data.data.map(async (val) => {
val = val.Client
let name = $.trim(val.business_name);
let code = $.trim(val.client_number);
if (name == clientName && code == clientCode) {
clientPhone = await val.phone2
console.log(clientPhone) //logs *clients' phone*
return clientPhone
}
})
})
}
async function myApp() {
let clientSet = new Set()
for (const [i, v] of Array.from($(".media-body")).entries()) {
let clientName = $.trim($(v).find("h3").text())
if (!clientSet.has(clientName)) {
clientSet.add(clientName)
clientPhone = await getAllClients(clientName)
console.log("------", clientPhone) //logs *undefined*
// Do some other functions
} else {
console.log(clientPhone) //logs *undefined*
// Do some other functions
}
}
}
//=============== App starts ================
$(document).ready(function () {
let clientPhone;
myApp()
})
</script>
In A Nutshell: I want to store the clientPhone
in its global variable for each iteration a request is sent to reuse its value for other items that repeat.