Search code examples
javascriptasynchronousxmlhttprequestsapui5

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


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?


Solution

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