javascript - 为什么 'toPromise()' 对我不起作用

标签 javascript angular ionic-framework rxjs es6-promise

我用代码示例解释了我的问题

我有以下服务:

@Injectable()
export class PartidoProvider extends MyFirestoreProvider<Partido> {

 constructor(  public http: HttpClient,
               public firestore: AngularFirestore) {      
    super('partidos', http, firestore);        
  }

 buscarPartido ( jugador1: Jugador, jugador2: Jugador ) : Observable<Partido[]> {
    let partidoGanaJugador1: Partido = new Partido();
    let partidoPierdeJugador1: Partido = new Partido();

    partidoGanaJugador1.jugadorGanador = jugador1.idDoc;
    partidoGanaJugador1.jugadorPerdedor = jugador2.idDoc;

    partidoPierdeJugador1.jugadorGanador = jugador2.idDoc;
    partidoPierdeJugador1.jugadorPerdedor = jugador1.idDoc;

    return Observable.zip(  this.get(partidoGanaJugador1), 
                        this.get(partidoPierdeJugador1), 
                        (listaGanados, listaPerdidos) => {                                  
                              return listaGanados.concat(listaPerdidos);
    });    
}

我需要从一个组件调用转换为 promise 的服务,以便稍后使用 await 等待数据返回,以便管理在另一个实体中的注册。

接下来我将展示调用服务的测试代码:

  async enviarResultado(){
    let rival: Jugador;
    let jugador: Jugador = this.authProvider.jugador;
    let nombreRival: string;
    let partido: Partido;
   // Obtener partido del calendario para añadirle el resultado    
    nombreRival = this.myForm.controls['rival'].value;        
    rival = this.rivales.find( rival => rival.nombre == nombreRival);    

    // THIS WORKS
    const sample = val => Observable.of(val).delay(5000);
    const example = sample('First Example').toPromise().then(result => {
     console.log('From Promise:', result);
          });

    // THIS WORKS
    this.partidoProvider.buscarPartido(jugador, rival).subscribe(
      resultado => {
        console.log("El subscribe ha devuelto datos");
        console.log(resultado);          
      },
      error => {
        console.error("Se ha producido un error al intentar buscar el partido para modificar el resultado")
      }
  );

   // THIS DOESN'T WORK only 1 appears in the debug console (console.log ("1"))
   console.log("1"); 
   this.partidoProvider.buscarPartido(jugador, rival).toPromise()
   .then( lista => {
     console.log("2");
     console.log("Promesa entra");
     console.log("data:" + lista);                      
     if ( lista && lista.length > 0){
       partido = lista[0]
     }
   })
   .catch( error => {
     console.log("2");
     console.error("Se ha producido un error al intentar buscar el partido para modificar el resultado")
    });    

有没有人知道哪里出了问题?

非常感谢您

最佳答案

当使用 toPromise() 时,您需要确保源 Observables 完成。

Observables 可以发出多个值,因此 toPromise() 无法知道最后一个值是什么以及何时应该解析它返回的 Promise。

所以我的猜测是使用 this.get(...) 创建的源 Observables 之一永远不会完成。也许您想使用类似这样的东西 Observable.zip(...).take(1)

关于javascript - 为什么 'toPromise()' 对我不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51707844/

相关文章:

javascript - 先前单击下一个按钮时,clickNextButton 未正确执行

javascript - jquery 为什么 body 点击不起作用?

angular - 无法在 Angular 项目上安装 typescript@4.9

angular - 我可以在多个 Angular2 表单中创建和重用 ControlGroup 组件吗

android - Ionic Facebook Api 无效的 key 散列

javascript - 受信任站点(IE8)中window.opener的问题

javascript - 用于时间跟踪的正则表达式验证

Angular 2 和全屏 API

android - 在 Ionic 2 中进行 HTTP POST 调用会给出禁止响应

android - 了解何时在 Android 中使用 cordova.file.externalRootDirectory