Skip to content

Instantly share code, notes, and snippets.

@dhananjayhegde
Created June 24, 2022 06:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhananjayhegde/2957958e7f90e621be2b09af5af47aa8 to your computer and use it in GitHub Desktop.
Save dhananjayhegde/2957958e7f90e621be2b09af5af47aa8 to your computer and use it in GitHub Desktop.
Wrap OData v2 model read into a Promise
sap.ui.define(
[], function(){
"use strict";
return sap.ui.controller("todo.app.todoapp1.ext.controller.ListReportExt", {
promiseToRead: function(sPath){
var oModel = this.oModel;
return new Promise(function(resolveCallback, rejectCallback){
oModel.read(sPath, {
success: resolveCallback,
error: rejectCallback
});
});
},
onClickActionTodo1: function (oEvent) {
this.oModel = this.getView().getModel();
var oPromisedToRead1 = this.promiseToRead("/Todo"); // EntitySet name
var oPromisedToRead2 = this.promiseToRead("/Subtask"); // EnttiySet name
Promise.all([
oPromisedToRead1,
oPromisedToRead2
]).then(function(aData){
console.log("all promises are done");
/**
* aData is an array that contains result of both oModel.read() calls
* aData[0] -> result of first read() call
* aData[1] -> result of second read() call
*/
console.log(aData);
});
}
});
});
@dhananjayhegde
Copy link
Author

Notice the function promiseToRead which returns a new Promise every time it is called.

  • when the ODATA read call is success, this promise is resolved (calling resolveCallback),
  • when it fails, promise is rejected (calling rejectCallback)

To ensure that we do something only when BOTH the calls are successful, use Promise.all( [ ] ).then( ).
aData is an array which contains the response of both OData calls. Callback function on line 27 is called only when both the promises are resolved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment