![](/img/trans.png)
[英]Vue JS computed property is undefined (async axios call in vuex)
[英]The result of an async function is undefined in JS using AXIOS
我正在嘗試從連接到 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("/");
}
};
您沒有從getNotesFromDB
函數返回任何內容,您應該返回 axios 調用的結果:
export async function getNotesFromDB(googleId) {
let answer;
return await axios
// Rest of the function body ....
你可以只返回承諾並處理錯誤
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.