简体   繁体   English

为什么'toPromise()'对我来说不起作用

[英]Why the 'toPromise()' doesn't work for me when

I explain my problem with the code example 我用代码示例解释了我的问题

I have the following service: 我有以下服务:

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

From a component I need to invoke the service converted to a promise to later use await to wait for the data to return in order to manage the registration in another entity. 从一个组件我需要调用转换为promise的服务,以便稍后使用await等待数据返回,以便管理另一个实体中的注册。

Next I show the code of tests of the calls to the service: 接下来,我将展示对服务调用的测试代码:

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

Does anyone have any idea what is wrong? 有谁知道什么是错的?

Thank you very much in advance 非常感谢你提前

When using toPromise() you need to be sure that the source Observables completes. 使用toPromise()您需要确保源Observables完成。

Observables can emit multiple values so toPromise() can't know what is the last value and when it should resolve the Promise it returns. Observable可以发出多个值,因此toPromise()无法知道最后一个值是什么,何时应该解析它返回的Promise。

So my guess is that one of the source Observables created with this.get(...) never completes. 所以我的猜测是用this.get(...)创建的其中一个源Observable永远不会完成。 Maybe you want to use something like this Observable.zip(...).take(1) . 也许你想使用像这样的Observable.zip(...).take(1)

The toPromise function is actually a bit tricky, as it's not really an “operator”, rather it's an RxJS-specific means of subscribing to an Observable and wrap it in a promise. toPromise函数实际上有点棘手,因为它不是真正的“运算符”,而是一种特定于RxJS的订阅Observable并将其包装在promise中的方法。 The promise will resolve to the last emitted value of the Observable once the Observable completes. 一旦Observable完成,promise将解析为Observable的最后一个值。

https://medium.com/@benlesh/rxjs-observable-interop-with-promises-and-async-await-bebb05306875 https://medium.com/@benlesh/rxjs-observable-interop-with-promises-and-async-await-bebb05306875

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

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