我有以下代码
const link =
"https://www.daft.ie/property-for-rent/ireland?location=dublin&location=dublin-city&sort=publishDateDesc";
async function getLinks(url) {
return fetch(url)
.then((res) => res.text())
.then((html) => {
const $ = cheerio.load(html);
const sel = '[data-testid="results"] a[href]';
var links = [...$(sel)].map((e) => e.attribs.href);
return Promise.all(links);
});
}
getLinks(link).then(function(links) {
console.log(links);
});
这会返回一个类似的对象数组
[
'/for-rent/apartment-105-cabra-road-phibsborough-dublin-7/4071977',
'/for-rent/apartment-weavers-hall-leopardstown-dublin-18/4073220',
]
我希望它作为字符串数组返回,这样我就可以更容易地执行比较操作,并且可以将数组存储在变量中。
我还想知道如何在这个中使用await
我希望它能像这样工作,但目前失败了
const a = await getLinks(link1);
const b = await getLinks(link2);
其中CCD_ 2和CCD_。
我该怎么做?
您可以使用内置的URL api获取URL的第一部分:
const link = "https://www.daft.ie/property-for-rent/ireland?location=dublin&location=dublin-city&sort=publishDateDesc";
const url = new URL(link);
console.log(url.protocol + "//" + url.host);
然后你可以把你得到的链接附加到这个:
const url = new URL(link);
const a = await getLinks(url.protocol + "//" + url.host + link1);
const b = await getLinks(url.protocol + "//" + url.host + link2);
如果您想在顶级使用await
,并且环境不支持顶级等待,那么是的,您必须创建一个异步IIFE:
(async () => {
// your code
})();
不能调用await
,除非它在async
上下文中。这就像在非Promise对象上调用then
。您可以将其封装在匿名异步方法中,例如:
(async () => {
const a = await getLinks(link1);
const b = await getLinks(link2);
// do something
})()
或使用Promise.all:
(async () => {
const [a, b] = await Promise.all([getLinks(link1), getLinks(link2)]);
// do something
})()
在Promise失败的情况下,强烈建议将await
的使用封装在try...catch
块中,这也是一种最佳做法。