我的以下效果是试图完成以下任务:
不幸的是,我的以下代码似乎不尊重异步/等待,并且一旦效果运行完毕,我最终得到一个空数组。有什么想法我可能做错了吗?
useEffect(() => {
const types = ["jobs", "postings", "sale_items"];
async function getEntityReferencesAsync() {
let running_total = [];
types.forEach(
function(type) {
let open = [];
let closed = [];
let therest = [];
const request = await get_data(
`https://myapi.com.com/${type}/${props.id}`
);
response.then(
function(result) {
const result_array = result.data.records;
result_array.forEach(
function(item) {
item["type"] = type;
if (item.status === "open") {
open.push(item);
} else if (item.status === "closed") {
closed.push(item);
} else {
therest.push(item);
}
}.bind(this)
);
running_total = [
...running_total,
...open,
...closed,
...therest
];
}.bind(this)
);
}.bind(this)
);
return running_total;
}
async function getSortedData() {
const sorted_array = await getEntityReferencesAsync();
setEntityReferencesData(sorted_array);
}
getSortedData();
}, [props.id]);
仅供参考,我的get_data函数如下:
async function get_data (endpoint, params) {
if (params === null) {
return await axios.get(endpoint)
} else{
return await axios.get(endpoint, {params: params});
}
};
答案 0 :(得分:0)