[英]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.