I am trying to return a string from a typescript function -
private _renderListAsync(): string {
let _accHtml: string='';
// Local environment
if (Environment.type === EnvironmentType.Local) {
this._getMockListData()
.then((response) => {
_accHtml = this._renderList(response.value);
alert("1: " + _accHtml)
})
alert("3: " + _accHtml);
return _accHtml;
}
else if (Environment.type == EnvironmentType.SharePoint ||
Environment.type == EnvironmentType.ClassicSharePoint) {
this._getListData()
.then((response) => {
_accHtml = this._renderList(response.value);
alert("2: " + _accHtml);
})
alert("3: " + _accHtml);
return _accHtml;
}
}
However, I am only able to get the string value for alerts with "1" and "2" but not "3" where the alert is empty, hence I am not able to return _accHtml from the function. What am I doing wrong? Also I notice that alert with "3" shows up before "1" and "2", why is that?
This happens because ".then(...)" is a process asynchronous,it opens new thread, and continues execute next lines of the method, it shows 3 before 2 and 1. I recomend that use Observables