繁体   English   中英

Promise 链接未返回预期结果

[英]Promise chaining not returning expected result

我必须为某些用户发送电子邮件。 我有一个 promise 返回用户 ID,另一个返回用户电子邮件(基于用户 ID)。 我将所有这些链接起来,但我的父母 function 得到一个空数组。

我尝试了承诺和异步等待,但我对此几乎没有经验,我不知道我在哪里失踪。

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。我无法访问数组项。

您的问题是,当第一个 function 返回时,不能保证数组被填充。 那是因为您从不等待 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)
    }
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM