javascript - 为什么 Promise 返回也 Resolve on Reject
问题描述
有人可以解释一下,为什么 Promise 在调用拒绝时会触发 then() 函数(以及 catch() 函数)?
调用 resolve 时,只有 then() 才会触发 - OK
调用拒绝时,调用 then() 和 catch() 函数 - 问题
static logIn(email, password) {
async function getSession () {
let data = new FormData();
data.append('email', email);
data.append('password', password);
const response = await fetch(
url,
{
method: 'POST',
mode: 'cors',
body: data,
cache: 'no-cache',
headers: {
'Accept': 'application/json',
},
}
);
const json = await response.json();
return json;
}
return new Promise((resolve, reject) => {
getSession()
.then(json => {
if (json.status === 'ok') {
resolve('OK');
} else {
reject('LogIn failed.');
}
})
.catch(error => reject('LogIn failed.'))
});
};
logIn()
.then(console.log('logged in'))
.catch(error => console.log('not logged in'));
解决方案
注意这一行:
.then(console.log('logged in'))
then
方法需要一个回调,但您正在调用一个函数并将return
值作为参数传递。如果console.log 返回一个函数,该函数将在内部调用then
,以防promise 被解决。但事实并非如此,因为 console.log 没有返回值!(它只是打印并退出)。
在 javascript 中,没有返回值等于undefined
. 因此,您正在做的是在任何情况下调用 console.log并将 undefined 作为参数传递。因此,您的代码等效于:
console.log('logged in');
...
.then(undefined)
...
可能,您的意思是将日志回调作为参数传递,并让Promise在解决时调用该回调:
.then(() => console.log('logged in'));
或者,为了更清楚地了解正在发生的事情,您可以这样查看:
function log() {
console.log('logged in');
}
...
.then(log);
我们没有调用函数,只是传递引用!
推荐阅读
- css - css 的 @media 屏幕在 Visual Studio 2015 中不起作用
- c# - C# - 从任何字符串中查找 unicode 代码点的代理对的正则表达式?
- keras - 递归神经网络:这两篇文章中不同的numpy reshape?
- ruby-on-rails - 无法清除活动存储附件
- r - 将 tidyquant 数据与 quantstrat 一起使用
- sql - CASE 语句根据滞后/领先行在 BQ 中的分区内创建另一个窗口
- javascript - Vue.Draggable 不移动组件
- github - Git 提交未显示在我分叉的 repo 上
- visual-studio-extensions - 如何适应 Visual Studio 2019 的扩展?
- macos - OSX命令行:在运行之前回显命令吗?