我在名为 accountManager 的服务中有一个函数返回如下所示的 promise :
这个 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);
})
}
当我在另一个使用此 signIn 方法的类(class)时,问题就出现了。 promise 中的响应现在为空。当我从函数本身省略 promise 时,返回的 promise 的 .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;
})
有谁知道为什么在返回 promise 时 promise .then() 包含一个值,但返回给出的 promise 在它的 .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`
});
返回值也可以是另一个 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
});
关于javascript - 第二个 .then() on promise 被调用时数据未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44491352/