0

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

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”之前,这是为什么呢?

4

1 回答 1

0

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

于 2017-04-19T15:37:19.863 回答