javascript - 为什么 Promise 在 Reject 时也会返回 Resolve

标签 javascript promise async-await ecmascript-2017

有人可以解释一下,为什么 Promise 在调用拒绝时会触发 then() 函数(还有 catch() 函数)?

当调用resolve时,只有then()被触发 - OK

当调用reject时,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 方法需要 callback ,但您正在调用一个函数并将返回值作为参数传递。如果 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);

我们没有调用该函数,只是传递引用!

关于javascript - 为什么 Promise 在 Reject 时也会返回 Resolve,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50100708/

相关文章:

javascript - 如何暂停 jQuery 中的事件?

javascript - 如何在 jQuery 中使用数据属性值作为 ID 选择器?

javascript - Angular 嵌套 Promise

javascript - Promise - 在两个 Promise 之间调用一个函数

angularjs - $q.all 和创建新对象在 View 中不起作用

Javascript mailto 使用窗口打开

javascript - 从 CoffeeScript javascript if 语句中中断

asp.net-mvc-4 - Async 和 Await Action 方法。不异步工作。不知道原因吗?

javascript - 无法将上传的图像保存到 Hapi.js 中的数据库

c# - WPF 中的并行任务