使用 AXIOS 在 JS 中未定义异步函数的结果

Alo*_*kov 2 javascript frontend node.js reactjs axios

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

我在前端使用 React,并使用 Axios 处理 HTTP 请求。

我有 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;
    });
Run Code Online (Sandbox Code Playgroud)

}

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("/");
    }
  };
Run Code Online (Sandbox Code Playgroud)

小智 6

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

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