setLoading在获取所有数据之前被调用。如何确保仅在获取数据的for循环完成后才调用setLoading?甚至建议将异步数据与非异步数据组合在一起吗?我要实现的目标是为每个事件绘制一个时间轴,并附上它们各自的方向(即异步数据)
const Schedule = (props) => {
const [events, setEvents] = React.useState([]);
const [visible, setVisible] = React.useState(false);
const [unsatisfied, setUnsatisfied] = React.useState("");
const [timingsArray, setTimingsArray] = React.useState([]);
const [isLoading, setLoading] = React.useState(true);
React.useEffect(() => {
directionsArray(props.initRoutes, props.timings, props.data);
}, []);
const directionsArray = async (allRoutes, timings, data) => {
let result = [];
for (let i = 0; i < allRoutes.length - 1; i++) {
let obj = { distance: "", duration: "", steps: [] };
let steps = [];
let distance = "";
let duration = "";
let origin =
typeof allRoutes[i] === "object"
? allRoutes[i].lat + "," + allRoutes[i].long
: allRoutes[i];
let destination = allRoutes[i + 1];
try {
let resp = await fetch(
"https://maps.googleapis.com/maps/api/directions/json?origin=" +
origin +
"&destination=" +
destination +
"&key=" +
GOOGLE_MAPS_API_KEY +
"&mode=transit®ion=sg"
);
//console.log(JSON.stringify(await resp.json()));
let data = (await resp.json())["routes"][0]["legs"][0];
let response = data["steps"];
distance = data["distance"]["text"];
duration = data["duration"]["text"];
for (let j = 0; j < response.length; j++) {
steps.push(await routeFormatter(await response[j]));
}
} catch (err) {
console.log(err);
}
obj.steps = steps;
obj.distance = distance;
obj.duration = duration;
result.push(obj);
}
let updatedTimings = merge(timings, result);
let combinedData = eventsWithDirections(updatedTimings, data, result);
setTimingsArray(updatedTimings);
setEvents(combinedData);
setLoading(false);
};
if (isLoading) {
return (
<View
style={{
flex: 1,
alignContent: "center",
justifyContent: "center",
}}
>
<ActivityIndicator
style={{ alignSelf: "center" }}
size="large"
/>
</View>
);
} else {
return (
<View style={styles.container}>
<View style={styles.body}>
<Modal animated visible={visible} animationType="fade">
<ActionOptions
onReselect={onReselect}
onClose={onClose}
unsatisfied={unsatisfied}
events={props.allEvents}
genres={props.genres}
newTimeChange={newTimeChange}
filters={props.filters}
/>
</Modal>
<Timeline
onEventPress={(event) => onEventPress(event)}
data={events}
timeStyle={{
textAlign: "center",
backgroundColor: "#cc5327",
color: "white",
padding: 5,
borderRadius: 13,
}}
/>
</View>
<View style={styles.footer}>{renderProceedButton()}</View>
</View>
);
}
};
答案 0 :(得分:0)
我认为这里的问题是,在 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
java.util.Date fechainicioutil;
java.util.Date fechafinalutil;
String codsocio = txtcodsocio.getText();
int intcodsocio = Integer.parseInt(codsocio);
String codlibro = txtcodsocio.getText();
int intcodlibro = Integer.parseInt(codlibro);
fechainicioutil = fechainicio.getDate();
fechafinalutil = fechafinal.getDate();
java.sql.Date fechainiciosql = new java.sql.Date(fechainicioutil.getTime());
java.sql.Date fechafinalosql = new java.sql.Date(fechafinalutil.getTime());
try {
String sql = "INSERT INTO reservas (codsocio, codlibro, fechainicioreserva, fechadevolucion) "
+ "VALUES (?,?,?,?)";
Connection reservarlibro = new Conexion().conectar();
PreparedStatement st = reservarlibro.prepareStatement(sql);
st.setInt(1, intcodsocio);
st.setInt(2, intcodlibro);
st.setDate(3, fechainiciosql);
st.setDate(4, fechafinalosql);
st.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
System.out.println(e);
上循环的循环需要包装在allRoutes
中。现在,在循环的每次迭代中,Promise.all
块中的其余代码将等待数据被提取,但是try
在该作用域之外被调用,并且不会被告知setLoading
其他。
而不是for循环,也许尝试让迭代类似于
await
希望如此。我发现该帖子对主题也有帮助:https://zellwk.com/blog/async-await-in-loops/