【问题标题】:Promise chaining not returning expected result承诺链接不返回预期结果
【发布时间】:2019-09-20 03:35:05
【问题描述】:

我必须为某些用户发送电子邮件。我有一个返回用户 ID 的承诺和另一个返回用户电子邮件(基于用户 ID)的承诺。 我有所有这些链接,但我的父函数得到一个空数组。

我尝试了 promise 和 async await,但我对此没有什么经验,而且我不知道我错过了哪里。

private async _getUserFromContatos(_subtipoEmergenciaID: number):Promise<string[]>{

  const _arrTo: string[] = [];

  sp.web.lists.getByTitle("Contato").items.get().then((items:any[]) => {
    let _contatos = items.filter((i) => i.SubtipoEmergenciaId == _subtipoEmergenciaID);
   _contatos.map(c => {
      sp.web.getUserById(c.FuncionarioId).get().then(_userInfo => {
        _arrTo.push(_userInfo.Email);
      });
    });

  });
  return _arrTo;
}


private _sendMail(){
   this._getUserFromContatos(this.state.selectedSubtipoEmergencia).then( 
  _arrTo => {
    console.log(_arrTo); //Returns the array as if its filled ok
    console.log(_arrTo.length); //Returns 0 (empty array)
    });

}

最后的第一个 console.log 返回填充的数组,但第二个返回 0。 我无法访问数组项。

【问题讨论】:

    标签: reactjs typescript sharepoint promise spfx


    【解决方案1】:

    您的问题是第一个函数返回时不能保证数组被填充。那是因为您从不等待 getUserById 调用的结果。 这里有两种可能的解决方案(一种使用 await / 一种不使用 await)

    function _getUserFromContatos(_subtipoEmergenciaID: number): Promise<string[]> {
      return sp.web.lists
        .getByTitle("Contato")
        .items
        .get()
        .then((items: any[]) => {
          let _contatos = items.filter(i => i.SubtipoEmergenciaId == _subtipoEmergenciaID);
    
          return Promise.all(
            _contatos.map(c => {
              sp.web
                .getUserById(c.FuncionarioId)
                .get()
                .then(_userInfo => _userInfo.Email);
            })
          );
        });
    }
    
    async function _getUserFromContatos(_subtipoEmergenciaID: number): Promise<string[]> {
      var items = await sp.web.lists.getByTitle("Contato").items.get(); // await the list
    
      let _contatos = items.filter(i => i.SubtipoEmergenciaId == _subtipoEmergenciaID);
    
      var _arrTo: string[] = [];
      for (var c of _contatos) {
          var userInfo = await sp.web.getUserById(c.FuncionarioId).get(); // query every user and await that result
          _arrTo.push(userInfo.Email);
      }
    
      return _arrTo;
    }
    
    function _sendMail() {
      this._getUserFromContatos(this.state.selectedSubtipoEmergencia).then(
        _arrTo => {
          console.log(_arrTo); //Returns the array as if its filled ok
          console.log(_arrTo.length); //Returns 0 (empty array)
        }
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-15
      • 1970-01-01
      • 2023-01-27
      • 1970-01-01
      • 2017-04-02
      • 2014-11-24
      • 2017-02-03
      • 2019-10-20
      • 2019-02-06
      相关资源
      最近更新 更多