Thursday, October 20, 2022

[FIXED] How to make wait till API call completed in javascript

Issue

I need to make API inside the map function. code is not waiting to complete the map function loop when i use the setTimeout function. In this below code "All api action completed" log should show after completed the API call with setTimeout. kindly suggest the solution.

    async function FieldMapping() {
        let data = [
            {
                "contractID": "D3047-IND-001",
                "fieldValues": {
                    "custrecord_vgicp_add_insurance_expense": "3000",
                    "custrecord_vgicp_advancespaid": "2000",
                    "custrecord_vgicp_allow_food_other": "3000"
                }
            },
            {
                "contractID": "D3048-IND-003",
                "fieldValues": {
                    "custrecord_vgicp_add_insurance_expense": "3700",
                    "custrecord_vgicp_advancespaid": "3700",
                    "custrecord_vgicp_allow_food_other": "3700"
                }
            },
            {
                "contractID": "D3049-IND-001",
                "fieldValues": {
                    "custrecord_vgicp_add_insurance_expense": "3700",
                    "custrecord_vgicp_advancespaid": "3700",
                    "custrecord_vgicp_allow_food_other": "3700"
                }
            },
            {
                "contractID": "D3081-FRA-002",
                "fieldValues": {
                    "custrecord_vgicp_add_insurance_expense": "3700",
                    "custrecord_vgicp_advancespaid": "3700",
                    "custrecord_vgicp_allow_food_other": "3700"
                }
            },
            {
                "contractID": "D3106-IND-002",
                "fieldValues": {
                    "custrecord_vgicp_add_insurance_expense": "2000",
                    "custrecord_vgicp_advancespaid": "2000",
                    "custrecord_vgicp_allow_food_other": "2000"
                }
            }
        ]
    
        await Promise.all(data.map(async(payroll, index)=> {
            setTimeout(async () => {
                let result = await apiCall(payroll)
                console.log("result:::", result)
            }, 1000*index+1 )
 
        }))
console.log("All API Action completed...")
    }
    
    async function apiCall() {
        //api call here
    }

Solution

You need to return a promise from the map callback

    await Promise.all(data.map(async(payroll, index) => {
        return new Promise((resolve, reject) => setTimeout(async() => {
            try {
              let result = await apiCall(payroll)
              resolve(result)
            } catch (e) {
              reject()
            }
        }, 1000 * index + 1)

     }))



Answered By - Mina
Answer Checked By - David Marino (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.