【发布时间】:2020-10-25 14:04:51
【问题描述】:
我有一个返回 Promise 的函数,在这个 Promise 中我得到了一个解析对象。 这是我的服务的功能很好。
buscarUsuario(email: string){
return new Promise((resolve, reject) => {
this.http.post(`${URL}/user/email`, {email})
.subscribe(resp => {
//console.log(resp['usuario']);
resolve(resp['usuario']);
});
})
}
然后我从这个var中的promise中得到值:
const getDatos = this.usuarioService.buscarUsuario(this.correoUsuario.value.toString());
然后我调用 var 从解析中获取值,但我无法从那里提取该值:
var usuario: Usuario;
getDatos.then(usu => {
usuario = usu;
//Here I can see the value
console.log(usuario);
});
//But here I can't see the value
//And it's where I really need to get the value
console.log(usuario);
那么,我如何在 Promise 之外获得该值?
【问题讨论】:
-
1.您正在使用the promise constructor antipattern 2. 一旦函数返回一个承诺,您总是必须将其视为异步的。没有办法将其转换回同步。因此,您需要
await它或使用 Promise API 来使用产生的值。见Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference -
我对 Promise 还很陌生,我现在不知道如何使用 await,那么我该如何等待呢?
-
const getDatos = await this.usuarioService.buscarUsuario(this.correoUsuario.value.toString());
标签: node.js angular typescript http post