我想在axios.post
成功时中断循环。我该怎么办?
for (var i = 0; i < filteredCars.length; i++) {
var car = filteredCars[i];
axios
.post(
"http://localhost:9000/api/cars/" + car.id + "/createReservation",
{
pick_up_date: "July 29, 2023 03:00:01",
drop_off_date: "July 30, 2023 09:00:00"
},
config
)
.then(response => {
this.setState({
reserved: true
});
})
.catch(error => {
console.log(error);
});
}
答案 0 :(得分:1)
您最好的选择是在异步函数中使用await
。因此,您的方法如下:
async function testFunction() {
for (var i = 0; i < filteredCars.length; i++) {
var car = filteredCars[i];
var response = await axios.post("http://localhost:9000/api/cars/" + car.id + "/createReservation";
this.setState({ reserved: true });
if (conditionToBreak === true) {
break;
}
}
}