打字稿返回值

时间:2017-04-19 14:55:30

标签: typescript sharepoint-2016

我正在尝试从打字稿函数返回一个字符串 -

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

但是,我只能通过" 1"获取警报的字符串值。和" 2"但不是" 3"警报为空的地方,因此我无法从函数返回_accHtml。我究竟做错了什么?我还注意到" 3"出现之前" 1"和" 2",为什么会这样?

1 个答案:

答案 0 :(得分:0)

这是因为" .then(...)"是一个异步的进程,它打开新的线程,并继续执行该方法的下一行,它在2和1之前显示3。我建议使用Observables