I'm having issues returning a created Object the code is below:
Within the Promise.allSettled, I eventually get the results which I loop over and push each array to an object (This creates the object fine), when I try and return that said object, it's empty.
I think it's because my promise hasn't settled, I've tried doing:
Promise.resolve(returnedData) then returning it, and even .then(results => results).
What am I missing? I think I've looked at this for so long there's something clear as day I'm missing.
const getProductData = () => {
debugger;
const productIds = [];
const returnedData = [];
const customerLocation = getCustomerLocation();
productdataItems.forEach((product) => {
productIds.push(
product
.querySelector('[data-test-id="product-card-code"]')
.innerHTML.replace(/[^0-9]/g, ''),
);
});
const items = productIds.map((product) => ({
productCode: product,
quantity: 1,
}));
// Load in products for other steps
const promises = [];
productIds.forEach((sku) => {
promises.push(getProduct(sku));
});
Promise.allSettled(promises).then((results) => {
// Stock requires location data.
if (customerLocation) {
getEligibility(items, customerLocation).then((eligibility) => {
getStock([customerLocation.collectionBranchId], productIds).then(
(stock) => {
results.forEach((result, i) => {
if (result.value.product) {
returnedData.push({
Product: result.value.product,
Eligibility: eligibility[i],
Stock: stock[i].quantity,
ProductMarkup: productdataItems,
PostCode: customerLocation.deliveryPostcode,
});
}
});
},
);
});
}
});
return returnedData;
};
returnedData is outside the promise.allSettled. So it is getting returned before the Promise.allSettled completes and hence it is empty.
What you should be doing is moving the return of returnData inside Promises
return Promise.allSettled(promises).then((results) => {
... ...
return returnData;
}
The getProductData needs to be a async method that returns a promise result.