【发布时间】:2018-10-29 02:05:05
【问题描述】:
因此,基本思想是编写一个方法,该方法将废弃网页以获取包含产品评级的 JSON 数据。然后在几个域(.de、.uk、.fr、.nl 等)上多次调用此方法以收集所有评级。
所以我最终使用了 scrapWebPage 方法,该方法会删除单个页面:
const scrapWebPage = async (countryAppData, productNumber) => {
const shopUrl = `https://www.shopExample.${countryAppData.countryCode}/?q=${productNumber}`
const avoidCORSUrl = 'https://allorigins.me/get?url=' + shopUrl + '&callback=?'
return await axios
.get(avoidCORSUrl, {xmlMode: false, normalizeWhitespace: true})
.then(response => {
const $ = cheerio.load(response.data)
let scrapedWebPageJson
contentForParsing = $("script").get().children[0].data
scrapedWebPageJson = JSON.parse(contentForParsing)
return scrapedWebPageJson
})
}
scrapWebPage 还包含一些解析以返回我想要的一些 JSON 数据 - 它正确解析(经过测试)并返回 Promise。
但后来我想在多个域上调用此方法,所以我创建了getProductDataFromManyDomains:
const getProductDataFromManyDomains = (productNum) => {
let prodData = {
reviews: []
}
const appCountries = [
{countryCode: 'nl'},
{countryCode: 'pl'},
{countryCode: 'de'}
]
appCountries.forEach(async countryApp => {
let countryData = {}
let parsedWebPage = await scrapWebPage(countryApp, productNum)
countryData.countryCode = countryApp.countryCode
countryData.ratingCount = parsedWebPage.aggregateRating.ratingCount
countryData.ratingValue = parsedWebPage.aggregateRating.ratingValue
countryData.reviews = parsedWebPage.reviews
prodData.reviews.push(countryData)
})
return prodData
}
现在我在填充之前收到prodData...而我想接收实际数据(填充prodData)。
我不确定我应该如何构造这个getProductDataFromManyDomains 方法来实际返回数据,而不是在填充之前prodData。那可能吗?或者这里有什么好的模式来处理这样的事情?
【问题讨论】:
-
使用
for循环而不是.forEach()。for循环将暂停await,.forEach()循环不会。然后,getProductDataFromManyDomains()将需要是异步的,并将返回一个带有最终结果的承诺。 -
@jfriend00 哇?!直到,谢谢!
-
@jfriend00 我不太明白你...我可以做
for (let countryApp of appCountries) {...}和getProductDataFromManyDomainsasync 但是我应该在这个方法中返回什么呢?我猜不是return prodData,因为它不会被填充...我迷路了:/ -
@stackustack - 代码示例放入下面的答案中。
-
使用同步请求从不同域拉取数据是个糟糕的主意。此类请求必须异步完成。
标签: javascript asynchronous promise async-await axios