I am trying to use async and await on my react js app. But it's not working correctly.
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);
};
I expected the requestData array after foreach. But that console.log does not occur after foreach, it occurs before foreach. That means async and await is not working. What's wrong in my code?