d33a
d33a

Reputation: 740

How to wait for the response of an OData service's read operation in SAPUI5 before further execution of code?

I have a function (say function1), which midway calls an OData call in another function (say function2). I have some process after the OData call in function1, which is dependent upon the response of the OData read call in function2.

Currently, during the execution of function1, when function2 is called, the function2 is executed but the OData response is only received after remaining lines of function1 are executed. Is there a way to await the response of the OData call in function2 before the remaining lines of function1 are executed?

I am super new to asynchronous programming. But what I have tried is:

function1: function() {
//some code
this.function2();
//some code & this is executed before success/error function of the OData call in function2
}

function2: async function() {
//oModel declaration
const oPromise = await new Promise((resolve, reject) => {
                        oModel.read("/entityset", {
                        success: (oData) => {
                            resolve(oData)
                        },
                        error: (oError) => {}
                    });
                    }).then((oData) => {
                        //some code
                    });
}

Upvotes: 1

Views: 5217

Answers (1)

Dorad
Dorad

Reputation: 3713

You are in a good direction. You should call function2 with an await statement within function1. A prerequisite for that is to make function1 async too:

function1: async function() {
//some code
await this.function2();
//some code & this will execute after success/error function of the OData call in function2
}

function2: async function() {
//oModel declaration
const oPromise = await new Promise((resolve, reject) => {
                        oModel.read("/entityset", {
                        success: (oData) => {
                            resolve(oData)
                        },
                        error: (oError) => {}
                    });
                    });
}

Upvotes: 3

Related Questions