I have an asynchronous function that calls another asynchronous function within it. This asynchronous function is returning "< pending >" instead of a value. Below is what I am getting.
temp [
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> }
]
Could you please help me solve this issue?
Here is the first asynchronous function:
router.get('/all', async (req, res, next) => {
ProductTable.getAllProducts()
.then(async ({ allProducts }) => {
const newAllProducts = await updateAllProducts(allProducts);
res.json({ allProducts });
})
.catch(error => next(error));
});
As you can see, I am calling updateAllProducts function and store that value into a variable call newAllProducts. updateAllProducts is another asynchronous function.
Here is the code for updateAllProducts:
const updateAllProducts = async (allProducts) => {
const temp = await allProducts.map(async (product, index) => {
const url = product.url;
const { currentPrice, newSizes } = await scrapeData(url);
const { currentAvailableSizes, unavailableSizes } = newSizes;
const long = product.availableSizes.length >= currentAvailableSizes.length ? product.availableSizes : currentAvailableSizes;
const short = product.availableSizes.length <= currentAvailableSizes.length ? product.availableSizes : currentAvailableSizes;
const availableSizesDiff = long.filter(x => short.indexOf(Number(x)) === -1);
product.currentPrice = currentPrice;
product.priceDiff = 1000;
product.currentAvailableSizes = currentAvailableSizes;
product.availableSizesDiff = availableSizesDiff;
});
return temp;
}
This updateAllProducts function is calling another asynchronous function call scrapeData within it.
ScrapeData function is just a function that uses puppeteer library to scrape data from a webpage. Here is the code:
const scrapeData = async (url) => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url);
const currentPrice = await page.evaluate(() => {
if(document.querySelectorAll('[data-test="product-price-reduced"]').length !== 0) {
return document.querySelectorAll('[data-test="product-price-reduced"]')[0].textContent;
} else {
return document.querySelectorAll('[data-test="product-price"]')[0].textContent;
}
});
const newProductInfo = { currentPrice };
return newProductInfo;
}