首页 > 解决方案 > 为什么 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'));

标签: javascriptpromiseasync-awaitecmascript-2017

解决方案


注意这一行:

.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);

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


推荐阅读