问题描述
我有一个 oDataModel ,并且正在读取具有 read 功能的特定属性。当读取的数据成功时,我将其分配给变量。但是总是说 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
}
解决方法
read
是异步的。当您执行oModel.read
时,它实际上会触发请求,但不会阻塞执行线程。如果您对上述代码进行调试,则会观察到console.log(locationID);
之后立即执行oModel.read
。此时,locationID
是undefined
(因为尚未发生分配)。分配仅在执行回调函数success
后发生。
要解决此问题,您可以将oModel.read
包装在Promise
中。您需要在成功中兑现诺言。
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))
}
我不确定语法的100%,但这应该有助于您走上正确的道路。