javascript - 如何在异步函数中从此返回的对象中提取数据?
问题描述
我正在尝试在 JavaScript 中做一些工作 - 我从异步函数调用异步函数,如下所示。
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())
返回了一个承诺,并且console.log(await asyncFunction())
什么也没有返回。
我注意到的一件奇怪的事情是,在程序的每个部分中放置 console.log 语句时,首先打印出来自函数调用(在 useEffect 块中)的承诺,然后是来自 console.log 语句的 reducer 中的数据补充一下return { errorMessage: "", data: action.payload };
。
所以我的问题是,我如何访问这些数据?我在这里查看了一些其他推荐使用的线程.then
,但没有成功。有没有办法在不传入回调函数的情况下做到这一点(这样做意味着我需要重组整个程序)。
这篇文章有点长,所以如果您有任何问题,或者需要我的程序的其他部分,请告诉我。
解决方案
您可以在不返回函数并直接完成其中的过程的情况下执行相同的过程。
修改使用效果代码如下:
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
}
因为在您提到的函数中,您将数据分派给reducer,而不是返回数据。因此,您可以在那里进行处理工作。
如果你想返回一些数据,你可以参考下面的代码:
以前的代码:
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将是从异步函数返回数据的最佳方式。
推荐阅读
- node.js - 使用 NodeJS 承诺等待转换完成
- database - MongoDB Webhook 函数将表单输入保存在数据库中
- microsoft-graph-api - @microsoft.graph.downloadUrl 有时不起作用
- c - 如何在c中打印文本文件的内容
- go - 如何在 Yocto 中构建 Go + C 代码,从配方中的文件中获取源代码
- python - 使用 Python 中的 Cloud Functions 将 CSV 数据从云存储加载到 Big Query 的最佳逻辑应该是什么
- authentication - 尝试在 localhost 上登录时出现 Amazon Pay Sandbox 错误 - “方案不是 HTTPS”
- javascript - 将字符串从 ajax 函数传递给 spring 控制器
- vb6 - Dir 函数错误“参数数量错误或属性分配无效”
- azure - 如何在线备份 Azure DevOps 源代码控制并还原到本地 Azure DevOps 服务器实例