【发布时间】:2019-01-12 19:46:12
【问题描述】:
我需要使用'await'等待服务返回数据。
服务的方法(PartidoProvider)是:
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);
});
校验数据时,需要等待上一个服务返回的数据。在下面的代码片段中,我放置了我正在使用的示例:
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 and return data
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 never returns data
console.log("1");
await 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")
});
console.log("3");
console.log("Partido encontrado:" + partido);
}
当它被执行并使用“订阅”调用服务时,它可以正常工作,但这不是我需要的。
当我用 await 调用它并使用方法“toPromise()”时没有返回任何数据,只有“console.log(“1”)的结果出现在调试控制台中。
调试控制台内容:
1
result-detail.ts:125 El subscribe ha devuelto datos
result-detail.ts:126
有人知道为什么会这样吗?
非常感谢您
【问题讨论】:
-
删除
then并记住await现在将返回lista,因此您需要执行let lista = await this.partidoProvider.buscarPartido(jugador,rival).toPromise()之类的操作
标签: javascript angular ionic-framework async-await