在Async / await函数中使用替换方法会引发错误Nodejs

问题描述 投票:-1回答:1

我当前在async / await函数中使用replace方法,并且在控制台中收到错误日志。我在YellowPages上进行了一些抓取,到目前为止,我已经有了所需的内容,但是当尝试通过删除'mailto:[email protected]'来清理像这样的字符串"mailto:"来清除电子邮件数据时,出现以下错误:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'replace' of undefined
    at Node.<anonymous> (/Users/aeum3893/Documents/test_scrapping/yellowpages_scraping/index.js:20:40)
(node:25401) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 8)

这是代码段

const getCompanies = async () => {
    try {
        const html = await rp(baseURL + searchURL);
        const businessMap = cheerio('a.business-name', html).map(async (i, e) => {
            const link = baseURL + e.attribs.href;
            const innerHtml = await rp(link);

            const emailAddress = cheerio('a.email-business', innerHtml).prop('href')
            const email = emailAddress.replace(/mailto:/, '');


            const name = e.children[0].data || cheerio('h1', innerHtml).text();
            const phone = cheerio('p.phone', innerHtml).text();

            const metadata = {
                emailAddress,
                link,
                name,
                phone,
            }
            parsedResults.push(metadata)
        })

删除删除方法后,一切正常。

感谢您的帮助,谢谢!

node.js web-scraping async-await cheerio
1个回答
0
投票

我尝试通过运行逻辑来替换和格式化电子邮件字符串,并且这样有效。

[在emailAddress变量之后立即运行替换逻辑时,我得到的预期结果不是不确定的,而是我想要的实际输出,但是当找到一家没有电子邮件的公司时,诺言就被拒绝了。我试图在emailAddress下方运行三元运算符,但两者均无效。

我发现解决方案是在实际的metadata对象中运行replace方法。现在一切正常。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.