我有一个异步函数,该函数在其中调用另一个异步函数。 此异步函数返回“ <未决>”而不是值。以下是我得到的。
temp [
Promise { <pending> },
Promise { <pending> },
Promise { <pending> },
Promise { <pending> }
]
能帮我解决这个问题吗?
这是第一个异步函数:
router.get('/all', async (req, res, next) => {
ProductTable.getAllProducts()
.then(async ({ allProducts }) => {
const newAllProducts = await updateAllProducts(allProducts);
res.json({ allProducts });
})
.catch(error => next(error));
});
如您所见,我正在调用updateAllProducts函数,并将该值存储到一个名为newAllProducts的变量中。 updateAllProducts是另一个异步函数。
这是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;
}
此updateAllProducts函数正在其中调用另一个异步函数调用scrapeData。
ScrapeData函数只是一个使用伪造的库从网页中抓取数据的函数。这是代码:
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;
}
答案 0 :(得分:0)
有了地图,您将得到Promise
的数组,其中Promise.all()
非常适合。完成所有承诺后,它就会完成,并为您提供结果列表。正如注释中已指出的,将进一步here进行说明。
在您的特定情况下,应该这样做:
const updateAllProducts = async (allProducts) => {
const temp = await Promise.all(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;
}