简体   繁体   中英

Promise chaining not returning expected result

I have to send an e-mail for some users. I have a promise that returns the users Ids and another that returns the users e-mails (based on user id). I have all of this chained but my parent function get an empty array.

I tried promises and async await but i have little experience with this and i dont know where im missing.

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

}

The first console.log at the end return the array filled but the second one returns 0. I cant access the array items.

Your problem is that the array is not guaranteed to be filled when the first function returns. That is because you never await the result of the getUserById call. Here are two possible solutions (one using await / one without 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)
    }
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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