【问题标题】:The result of an async function is undefined in JS using AXIOS使用 AXIOS 在 JS 中未定义异步函数的结果
【发布时间】:2021-10-29 15:20:37
【问题描述】:

我正在尝试从连接到 MongoDB 的服务器端获取客户端上的数据。

我在前端使用 React,在 HTTP 请求中使用 Axios。

我有 2 个文件,一个用于 API,一个是应用程序的 index.jsx。

我已成功从数据库中获取数据,但我在 index.jsx 上得到的结果始终未定义。

API 文件:

export async function  getNotesFromDB(googleId) {
let answer;
await axios
    .get(url + "/note/" + googleId, { withCredentials: true }) //WHEN LOCAL : http://localhost:5000/note/
    .then((notesDB) => {
        answer = notesDB; 
    })
    .catch((error) => {
        //Indicates the client of an error getting the notes from
        console.log(error);
         answer= null;
    })
    .finally( () => {
        return answer;
    });

}

index.jsx 文件:

import { getNotesFromDB as getNotesFromAPI } from "../API/Notes.jsx";
async function getNotesFromDB() {
    if (userInfo) {
      let googleId = userInfo.googleId;
      const result = await getNotesFromAPI(googleId);
      console.log(result);
 } else {
      history.push("/");
    }
  };

【问题讨论】:

    标签: javascript node.js reactjs axios frontend


    【解决方案1】:

    getNotesFromDB 函数没有返回任何内容,您应该返回 axios 调用的结果:

    export async function  getNotesFromDB(googleId) {
      let answer;
      return await axios
      // Rest of the function body ....
    

    【讨论】:

    • 哦,哇,我完全错过了我实际上没有返回任何东西。但即使我在等待之前添加了返回,它继续返回未定义。虽然当我使用 try/catch/finnaly 方法时它起作用了。
    【解决方案2】:

    你可以只返回承诺并处理错误

    export function getNotesFromDB(googleId) {
    return axios
        .get(url + "/note/" + googleId, { withCredentials: true }) //WHEN LOCAL : http://localhost:5000/note/
        .catch((error) => {
            //Indicates the client of an error getting the notes from
            console.log(error);
             return null
        })
    }
    
    

    export const getNotesFromDB = (googleId)  => axios
        .get(url + "/note/" + googleId, { withCredentials: true }) //WHEN LOCAL : http://localhost:5000/note/
        .catch((error) => {
            //Indicates the client of an error getting the notes from
            console.log(error);
             return null
        })
    
    

    或者如果你更喜欢使用 async/await

    export async function  getNotesFromDB(googleId) {
    try{
         const res = await axios.get(url + "/note/" + googleId, { withCredentials: true })
         return res 
       }catch(e){
         console.error(e);
         return null;
       }
    }
        
    

    【讨论】:

      猜你喜欢
      • 2020-08-23
      • 1970-01-01
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 2021-07-04
      • 2021-08-01
      • 2017-08-25
      • 1970-01-01
      相关资源
      最近更新 更多