【问题标题】:Axios not resolving, state is still a promiseAxios 没有解决,状态仍然是一个承诺
【发布时间】:2020-05-18 11:26:55
【问题描述】:

我使用 axios 已经有一段时间了,但我无法解决这个问题。 尝试了 axios 和 fetch 但它并没有解决我的承诺,我的状态仍然是一个承诺。

import axios from 'axios';

export const login = async (state, payload) => {

    try {
        const response = await axios.post('http://localhost:8080/token-auth/', payload)
        const data = await response.data



         return  {
            user: data.user,
            loggedIn: true,
            error: false
        }
    }


     catch (error) {
        return {
            user: null,
            loggedIn: false,
            error: true
        }

    }


}      const response = await axios.post('http://localhost:8080/token-auth/', payload)
        return  await response.data

    }


     catch (error) {
        return {
            user: null,
            loggedIn: false,
            error: true
        }

    }


}

它总是返回一个承诺而不是数据,但如果我console.log,我会在控制台上得到数据。

【问题讨论】:

  • 部分代码好像发了两次。
  • 在调用异步函数后你总会得到一个 Promise。要么在 await 语句之后执行操作,要么在调用 async 函数时使用.then
  • 显示与“您的状态保持承诺”相关的其余代码。您现在展示的是您进行 API 调用的方式,因此这并不能真正向我们展示全貌。

标签: javascript reactjs axios fetch state


【解决方案1】:

async 函数将始终返回承诺。

函数前面的“异步”一词意味着一件简单的事情:函数总是返回一个承诺。其他值自动包装在已解决的承诺中。

所以你必须在调用异步函数时处理 promise。

试试这个。

import axios from "axios";

export const login = async (state, payload) => {
  try {
    const response = await axios.post(
      "http://localhost:8080/token-auth/",
      payload
    );
    const data = await response.data;
    return {
      user: data.user,
      loggedIn: true,
      error: false
    };
  } catch (error) {
    return {
      user: null,
      loggedIn: false,
      error: true
    };
  }
};

(async function() {
  let response = await login(...);
  console.log(response);
})()

例子:

async function f() {
  return 1;
}


//Handle promise with then
f().then(console.log); // 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-20
    相关资源
    最近更新 更多