-3

I have one oDataModel and I am reading a particular property, with read function. When data read is success I am assigning it to a variable. But it is always saying undefined

readData : function(){
    var oModel = this.getView().getModel();
    var locationID;
    oModel.read('/Locations',{
       success: function(oData,oResponse){
          console.log(oData.results[0].id); //This is printing the data in console, properly
          locationID = oData.results[0].id;
       }
    });
    console.log(locationID); //This is printing as undefined
}
Boghyon Hoffmann
  • 17,103
  • 12
  • 72
  • 170
Badhusha
  • 195
  • 2
  • 20
  • See also [Why is my variable unaltered after I modify it inside of a function?](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Boghyon Hoffmann Aug 20 '20 at 06:17

1 Answers1

0

read is asynchronous. When you do oModel.read, it essentially fires the request but doesn't block the executing thread. If you do a debug of the above code, you'll observe that execution goes to console.log(locationID); immediately after oModel.read. At this point, locationID is undefined (Since assignment hasn't happened yet). The assignment only happens after the callback function success is executed.

To solve this, you can wrap your oModel.read within a Promise. You need to resolve your promise inside success.

readData: function() {
    var oModel = this.getView().getModel();
    var locationID;
    new Promise((resolve, reject) => {
        oModel.read('/Locations', {
            success: function (oData, oResponse) {
                console.log(oData.results[0].id);
                locationID = oData.results[0].id;
                resolve(locationID)
            },
            failure: function (oError) {
                reject(oError)
            }
        });
    }).then(data => console.log(data))
}

I'm not 100% sure of the syntax, but this should help put you on the right path.

Nitin
  • 1,279
  • 2
  • 10
  • 12