总的来说,我对 JavaScript/React 非常陌生,并且在和 的概念上苦苦Promise
挣扎async
。
首先,我有getSimById
一个 JS 文件中的 API 调用,它返回一个Promise
:
export function getSimById(simId) {
return fetch(simsUrl + "/results/" + simId, {
method: "GET",
headers: new Headers({
Authorization: "Basic " + base64.encode(login + ":" + password)
})
})
.then(handleResponse)
.catch(handleError);
}
并且handleResponse
是一个异步函数。
export async function handleResponse(response) {
if (response.ok) {
let someResponse = response.json();
return someResponse;
}
if (response.status === 400) {
throw new Error(error);
}
const error = await response.text();
throw new Error("Network response was not ok.");
}
现在我有一个返回的功能组件Table
:
import React, { useState, useEffect } from "react";
import { getSimById } from "../api/outrightSimulatorApi";
function SimulationReport(props) {
const location = useLocation();
const [simResult, setSimResult] = useState([]);
useEffect(() => {
getSimById(location.state.simId).then(result => setSimResult(result));
}, []);
let reformattedData = getSimById(location.state.simId).then(
data => reformattedData = data?.markets?.length ? data.markets.reduce(
(accumulator, market) =>
market.selections.map(({ name, probability }, index) => ({
...accumulator[index],
"Team name": name,
[market.name]: probability,
})),
[],
) : null);
return (
<div>
<Table striped bordered hover size="sm" responsive>
<thead>
<tr>{
}
</tr>
</thead>
<tbody>{
}
</tbody>
</Table>
</div>
);
在这段代码中,我想映射reformattedData
为一个数组,并最终映射到返回的Table
. 但是,reformattedData
在这种情况下,它不是一个数组,实际上是一个Promise
. 正因为如此,每当我尝试访问reformattedData[0]
它实际上返回的东西时undefined
,我都无法通过它在Table
. 在这种情况下,如何将 Promise 分配给变量,以便对其执行操作?