【问题标题】:Promise didn't get then branch承诺没有得到然后分支
【发布时间】:2018-04-13 08:24:16
【问题描述】:

我已经实现了这个函数来更新我在 firebase 上的用户,问题是它从不调用“then”函数......关于这个问题有什么建议吗?

用户在数据库中被正确更新,如果我尝试直接在函数上实现“then”分支,它会被触发。

编辑():

     // Proseguo con aggiornamento
     this.statoUtente.updateCurrentUser(uteIn).then(() => {

          <<<<<<<<<<<<<<<<<<<<< program never call this >>>>>>>>>>>>>>>>>

          console.log('Risposta da Promise') ;  
          // Dopo l'aggiornamento chiedo di completare le informazioni mancanti
          this.nomeTemplate = 'updateUserForm' ;
          this.helperset = 2 ;
          this.wait = false ;
          this.error = '' ;
      })




updateCurrentUser(UteIn : TipoSingoloUtente) : Promise<any> {

  let Promessa = new Promise<any>(observer => {
    let IDUtente = this.afAuth.auth.currentUser.uid ;
    console.log(IDUtente) ;
    if ((IDUtente) && ( IDUtente.trim() != '' )) {
      UteIn.ID = IDUtente ;
      observer(this.db.object('users/' + IDUtente).set(UteIn))
    } else {
      console.log('null null null') ;
      Promise.resolve(false) ;
    }
  }) ;

  return Promessa ;

}

【问题讨论】:

  • 你永远不会兑现你的承诺。承诺构造函数中的return 不会解析承诺。您需要以您的结果作为参数调用observer 函数。
  • 你为什么要使用 Promise?该代码中没有任何内容看起来是异步的。
  • @Bergi 我假设this.db.object('users/' + IDUtente).set(UteIn) 将是异步的。但是,如果这返回了一个承诺,那么您可以在另一个分支中返回它和 Promise.resolve(false)
  • @TylerSebastian...是的,this.db...返回一个承诺...如果我在函数内设置“then”分支,它会着火...如果我离开代码作为我的问题......它永远不会在函数之外调用 then 分支......我已经更新了“承诺解析的其他分支”
  • @CRice 好家伙,我只是将代码更新为:“observer(this.db.object('users/' + IDUtente).set(UteIn))”,它就可以工作了!跨度>

标签: angular typescript firebase promise angular-promise


【解决方案1】:

你只需要

updateCurrentUser(UteIn: TipoSingoloUtente) {
  const IDUtente = this.afAuth.auth.currentUser.uid;
  if (IDUtente && IDUtente.trim() != '') {
    UteIn.ID = IDUtente;
    return this.db.object('users/' + IDUtente).set(UteIn);
  } else {
    console.log('null null null');
    return Promise.resolve(false);
  }
}

您不需要将它包装在 Promise 构造函数中。 this.db.object... 返回 PromisePromise.resolve(...) 返回 Promise 所以你很好。

【讨论】:

  • 谢谢,这个解决方案也有效(而且比我的更简单)
【解决方案2】:

您应该删除您手动创建的承诺。没有必要。您只能使用由此返回的承诺:

this.db.object('users/' + IDUtente).set(UteIn)

当该承诺解决时,您可以确定数据库已更新。

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 2019-10-18
    • 2019-03-17
    • 2015-04-15
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多