Meatinboots
Meatinboots

Reputation: 41

Second Function finishes before First one

In following helper method I am trying to check current omni agent status, before updating it to new one.

 ({
handleStatus: function(cmp) {
    let action = cmp.get("c.checkCurrentTimeIsWithinBusinessHours");
    action.setCallback(this, function(response) {
        let state = response.getState();
        if (state === "SUCCESS") {
            setTimeout((() => {
                let omniAPI = cmp.find("omniToolkit");
//checkStatus
                    omniAPI.getServicePresenceStatusId().then(function(result) {
                        if(result.statusApiName != null){
                            cmp.set('v.isworking', true);
                        } else {
                            cmp.set('v.isworking', false);
                        }
                    }).then(updateStatus());
                }), 1000);
            } else {
                console.log(response.getError());
            }

//update status
            function updateStatus(){
                if (response.getReturnValue().isWorking && !cmp.get('v.isworking')){
                
                cmp.set('v.isworking', true);
                omniAPI.setServicePresenceStatus({statusId: response.getReturnValue().statusId.toString()}).then(function(result) {
                }).catch(function(error) {
                    console.log(error);
                });
            
            } else if (!response.getReturnValue().isWorking && cmp.get('v.isworking')){
                cmp.set('v.isworking', false);
                let omniAPI = cmp.find("omniToolkit");
                omniAPI.logout();
            }
        }
    });
    $A.enqueueAction(action);
}

})

As I understand async/await does not work in aura component and I dont belive that adding another settimeout to the 2nd function is a best practice. So basically changing status function finishes 1st and checking status - 2nd. Is there any way to set order of execution so that checking status finish before checking status? Thanks in advance.

Upvotes: 1

Views: 40

Answers (1)

grbeazley
grbeazley

Reputation: 198

You should pass the function to be called in the .then section, rather than calling the function. At the moment it will evaluate the updateStatus function at the same time as running omniAPI.getServicePresenceStatusId().

In your case update .then(updateStatus()) to .then(updateStatus);.

Upvotes: 0

Related Questions