0

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:

  1. To Send only to uniques without repeating. DONE using new Set()
  2. 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.

Taric Ov
  • 1
  • 2
  • Use the Promise from `$.get` alone, not the callback form - then, return the result of the `.map` call – CertainPerformance Sep 25 '22 at 00:25
  • That was my bad. didn't notice that `return` is scoped in the `.map` .. Just moved it out to the parent function scope and worked as it should. – Taric Ov Sep 25 '22 at 08:47

0 Answers0