In SAPUI5/OpenUI5, I have a JSONModel
I populate by a file from server:
var oModel = new JSONModel();
oModel.loadData("http://127.0.0.1/data/config.json");
console.log(JSON.stringify(oModel.getData()));
The console logs undefined
since the request is asynchronous.
How to make it synchronous so console.log()
is called after the data was loaded?
Since UI5 version 1.64.0, the API loadData
returns a Promise instance:
logLoadedData: async function () {
const jsonModel = new JSONModel();
await jsonModel.loadData("<host>/data/config.json");
console.log(jsonModel.getData()); // after the loadData promise is resolved
},
Alternatively, there is also the API dataLoaded
which returns a promise as well. It will resolve when all requests sent by loadData
are finished. Here is a syntax without async-await:
doSomethingWith: async function (jsonModel) {
// Not sure if the model has all data loaded? Just use dataLoaded:
await jsonModel.dataLoaded();
console.log(jsonModel.getData());
},
The API loadData
is also called internally when the constructor function of JSONModel
was called with a string (URL) as an argument. In that case, dataLoaded
might come in handy as well.
Using synchronous ajax requests is not recommended as it blocks the UI and will probably result in a warning in the console.
You can attach to the Model.requestCompleted
event to access the asynchronously loaded data:
oModel.attachRequestCompleted(function() {
console.log(oModel.getData());
});
The keyword you are looking for is "Deferred"-object --> it enables you to wait for an AJAX request in SAPUI5.
Check this for SAPUI5 context: SAPUI5 Wait for an Deferred-Object // wait for .done() function
You can use the attachRequestCompleted-listener from the Model [1]
model.attachRequestCompleted(function(){
console.log(this.getData()); //"this" is the model
});
Another function to use is
$.get(url, function(response){
console.log(response);
model.setData(response);
});
// or
$.ajax(url, {
success: function(){
console.log(response);
model.setData(response);
}
});
This has the advantage that you can configure the request with every setting that jQuery.ajax accepts [2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With