How to wait for a JSONModel.loadData() request in UI5

26,110

Solution 1

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());
    });

Solution 2

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

Solution 3

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.

Solution 4

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]

Share:
26,110
Benvorth
Author by

Benvorth

(HORACE, BK. V. Ode 3) (...) More than when, sunk in thought profound Of what the unaltering Gods require, My steward (friend but slave) brings round Logs for my fire. R. Kipling

Updated on November 13, 2021

Comments

  • Benvorth
    Benvorth over 2 years

    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?