Bla*_*ake 0 javascript arrays asynchronous async-await reactjs
我正在尝试在我的 react js 应用程序上使用 async 和 await。但它不能正常工作。
const handleFinish = async () => {
const startDateString = startDate.format('YYYY-MM-DDThh:mm');
const endDateString = endDate.format('YYYY-MM-DDThh:mm');
const createdString = moment().format('YYYY-MM-DDThh:mm');
const requestData = [];
const previousData = [];
selectedCustomerData.forEach(customer => {
selectedProductData.forEach(product => {
previousData.push({
customer: customer,
product: product
});
});
});
await previousData.forEach(async element => {
const tempStartDate = moment().add(element.customer.leadtime, 'days');
const apiUrl = '/productprice/?customerid=' + element.customer.customerid +
'&productkey=' + element.product.productkey +
'&isrulendNull=true';
await api.get(apiUrl).then(response => {
let newPrice = 0;
if (priceMethod === 'fixed') {
newPrice = price;
} else if (priceMethod === 'specific') {
newPrice = response.data[0].productpriceusd + price;
} else if (priceMethod === 'relative') {
newPrice = response.data[0].productpriceusd % 100.0 * (100.0 + price);
}
requestData.push({
productkey: element.product.productkey,
productcode: element.product.productcode,
customerid: element.customer.customerid,
customerchain: element.customer.customerchain,
productpriceusd: newPrice,
rulestart: (tempStartDate > startDate) ? tempStartDate.format('YYYY-MM-DDThh:mm') : startDateString,
ruleend: endDateString,
creatorupn: user.data.displayName,
created: createdString,
customername: element.customer.customername,
productdescription: element.product.productdescription,
});
});
});
console.log(requestData);
setPricesList(requestData);
};
Run Code Online (Sandbox Code Playgroud)
我期望 foreach 之后的 requestData 数组。但是console.log 不会在foreach 之后出现,而是在foreach 之前出现。这意味着 async 和 await 不起作用。我的代码有什么问题?
我自己也经常犯这个错误......
await previousData.forEach(async element => {
Run Code Online (Sandbox Code Playgroud)
这种东西确实不同步foreach循环。它们仍然是同时触发await
的,行首的 不等待它们。我会使用Promise.all
or 一个经典的循环,比如for
or while
。