[英]How can I extract data from this returned object in an async function?
我正在嘗試在 JavaScript 中做一些工作 - 我從異步 function 調用異步 function,如下所示。
useEffect(() => {
(async () => {
await asyncFunction();
// do stuff
})();
}, []);
asyncFunction 看起來像這樣
const asyncFunction = (dispatch) => {
return async (data) => {
try {
const response = await APICall();
dispatch({ type: "search", payload: response.data });
}
// error handling
}
asyncFunction 分派給reducer,reducer 返回return { errorMessage: "", data: action.payload };
通過我自己的測試,我看到console.log(asyncFunction())
返回了 promise,而console.log(await asyncFunction())
什么也沒返回。
我注意到的一件奇怪的事情是,在程序的每個部分中放置 console.log 語句時,首先打印出來自 function 調用(在 useEffect 塊中)的 promise,然后打印出來自 console.log 語句的減速器中的數據 I增加了關於return { errorMessage: "", data: action.payload };
.
所以我的問題是,我如何訪問這些數據? 我在這里查看了其他一些建議使用.then
的線程,但沒有成功。 有沒有辦法在不傳遞回調 function 的情況下做到這一點(這樣做意味着我需要重組整個程序)。
這篇文章有點長,所以如果您有任何問題,或者需要我的程序的其他部分,請告訴我。
您可以執行相同的過程,而無需返回 function 並直接在其中完成該過程。
修改使用效果代碼如下:
useEffect(() => {
(async () => {
await asyncFunction(dispatch);
// do stuff
})();
}, []);
const asyncFunction = async (dispatch, data) => {
try {
const response = await APICall();
dispatch({ type: "search", payload: response.data });
}
// error handling
}
因為在 function 中,您提到您正在將數據分派給減速器而不是返回數據。 因此,您可以在那里進行處理工作。
如果你想返回一些數據,你可以參考下面的代碼:
以前的代碼:
const asyncFunction = (dispatch, data) => {
return new Promise((resolve, reject) => {
APICall()
.then((reponse)=>{
dispatch({ type: "search", payload: response.data });
//This will return value to the calling function. This will act as a return statement
resolve(response);
})
.catch((err)=>{
//This will be executed if there is any error.
reject(err)
})
})
更改代碼(正如@Bergi 所說,以避免 Promise 構造函數反模式):
useEffect(() => {
let mounted = true;
APICall()
.then((response) => {
if (mounted) {
dispatch({ type: "search", payload: response.data });
//do some stuff here
}
})
.catch((err) => {
//handle error here
})
return () => mounted = false;
}, []);
Promise 是從異步function返回數據的最佳方式。
我可能完全錯了,但我認為您可能會遇到返回異步 function 的問題, 在 docs 中進行了解釋。
此外,看起來您可能正在調用 asyncFunction (在您的 useEffect 掛鈎內)而沒有調度值? 這里:
(async () => {
await asyncFunction();
// do stuff
我按照您的計划為 API 調用反芻了一個自定義鈎子: link to sandbox 。 希望它會有所幫助!
AsyncFunction 返回 function,而不是來自 API 調用的數據。 如果我正確理解您的問題,您可以做的是從調用中返回響應並刪除初始返回語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.