javascript - 如何直接从异步函数返回对象?
问题描述
- 我有 Redux 存储功能,我必须在其中创建 AJAX 并相应地更新状态。但是,我创建了以下函数,它在返回状态之前不会更新 x 值。所以,我创建了
async
函数。
var x =[]
lookup(
"GET",
"api/post/",
(response, status: number) => {
Object.assign(x, response);
}
);
console.log(x,'her x stay just ampty array []');
switch (action.type) {
case "SetData":
return { ...state, data: x };
default:
return state;
}
- 在下面的示例中,我试图在函数外部获取响应,
lookup
因此我创建了一个名为newData
how to make it rerun theres
directly without asining avar
inside的同步。
const newData = async () => {
var x: any = [];
await lookup(
"GET",
"api/post/",
(response: myArrays["posts"], status: number) => {
Object.assign(x, response);
}
);
return x;
};
console.log(newData().then((res) => res));
switch (action.type) {
case "SetData":
return { ...state, data: newData().then((res) => {return res}) };
default:
return state;
}
- 请注意:我不能在我的 store 函数中使用 React.usesState() 因为它不是一个组件函数。
解决方案
以您尝试执行此操作的方式执行此操作是不可能的。你需要做的是这样的:
const data = await newData();
dispatch({ type: "SetData", data })