s_k*_*les 5 javascript promise rxjs typescript angular
我在一个名为accountManager的服务中有一个函数,该函数返回如下所示的promise:
该承诺上的.then()会触发并打印出预期的响应。
signIn(email:String,password:String):Promise<any>{
return this.http.post('http://localhost:3000/api/signin',JSON.stringify({
"email": email,
"password": password
}),{headers: this.headers})
.toPromise()
.then(res => {
//**This is defined**
console.log(res);
})
}
Run Code Online (Sandbox Code Playgroud)
当我在另一个使用此signIn方法的类中时,就会出现问题。承诺内的响应现在为空。当我从函数本身省略承诺时,返回的承诺的.then()具有响应值。
if (this.loginForm.valid === true){
this.accountManager.signIn(this.email,this.password)
.then(response =>{
//**This .then has an undefined response when added on to the promise returned from the signIn function.**
let body = JSON.parse(response._body)
if (body.payload.success === true){
this.router.navigate(['/']);
}else{
this.signInError = true;
}
})
.catch(error=>{
this.signInError = true;
})
Run Code Online (Sandbox Code Playgroud)
有谁知道为什么在返回诺言但诺言给定的诺言中没有值的情况下,诺言.then()为何包含一个值?我很高兴澄清是否有任何令人困惑的地方。谢谢 :)
正如@cartant所说,console.log通话后您不会返回res 。从promise回调返回的值解析了promise。
new Promise(function(resolve) {
// this is almost equivalent
// to returning in promise callbacks
resolve(3);
})
.then(function(res) {
console.log(res); // logs 3
return 7;
})
.then(function(res) {
console.log(res); // logs 7
// no return, implicitly returns undefined
})
.then(function(res) {
console.log(res); // logs `undefined`
});
Run Code Online (Sandbox Code Playgroud)
返回的值也可以是另一个promise,因为随后的.then回调将监听该promise的解析:
new Promise(function(resolve) {
// this is almost equivalent
// to returning in promise callbacks
resolve(3);
})
.then(function(res) {
return Promise.resolve(5); // can create a Promise which resolves immediately
})
.then(function(res) {
console.log(res); // logs 5
});
Run Code Online (Sandbox Code Playgroud)