0

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;
};
pilchard
  • 12,414
  • 5
  • 11
  • 23
  • 1
    you're returning before allSettled is complete so it will always be empty. You'll need to await the `Promise.allSettled` for this to work. – pilchard Oct 29 '21 at 12:04
  • Like @pilchard is trying to explain, the problem is that functions passed as arguments to `then` are not executed immediately but are scheduled for later execution (not before all promises are well, settled, which may take a while, depending), they're effectively *callbacks*. So your `then` call on the promise returned by `Promises.allSettled` call, returns immediately, having registered a callback function that will be populating `returnedData`, with the crucial difference that when `then` returns, `returnedData` is still an empty array. That's what you're missing. – Armen Michaeli Oct 29 '21 at 12:06
  • 1
    You need to spend some time understanding JavaScript event loop and promises, specifically. It may take you a day, but it's worth it, otherwise you'll be encountering these kind of problems too frequently, I am afraid. – Armen Michaeli Oct 29 '21 at 12:08

1 Answers1

1

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.

Sagar Bhat
  • 111
  • 7