There are many different ways to read and process OData requests in JavaScript. Over time, the following approach has turned out to be the best and most robust for me personally.
Function
📟 _readexample of a get entity request.
📟 readDataasync function that calls the
_readfunction in atry...catchstatement and process the response of the request.
/**
* @memberOf Sample
* @private
* @async
* @description Read data from backend
* @param {string} sKey
*/
_read: function (sKey) {
var oServiceModel = this._oServiceModel;
return new Promise((fnResolve, fnReject) => {
var sPath = oServiceModel.createKey("/XYZSet", {
Key: sKey
});
var oParameters = {
success: fnResolve,
error: fnReject //,
//filters: [],
// urlParameters: {
// "$expand": "ASet"
// }
};
oServiceModel.read(sPath, oParameters);
});
},
/**
* @memberOf Sample
* @public
* @async
* @description Read the data.
* <ol>
* <li>read data via {@link Sample.read}</li>
* <li>if there are errors convert them via {@link Sample.convertExceptionToMessages}</li>
* </ol>
* @param {string} sKey - key
*/
readData: async function (sKey) {
var oResponse = {
success: true,
messages: []
};
//start the process/set busy indicator
this.setProperty("/busy", true);
try {
let oReadResponse = await this.read(sObjectId, sObjectType, sObjectSubType); //read Data from Backend
this.setProperty("/data", oReadResponse.results); //set data
} catch (oException) {
let aMessages = this.convertExceptionToMessages(oException); //convert exception to error message
oResponse.success = false;
oResponse.messages = aMessages;
} finally {
this.setProperty("/busy", false); //end the process/set busy indicator
}
return oResponse;
},
Example
Work in progress
Advantages
- easy way of processing the response
- easy way of catching exceptions
- easy way of handling busy states
