【问题标题】:code shows error await can only be declared inside async function although there is async function代码显示错误 await 只能在异步函数中声明,尽管有异步函数
【发布时间】:2023-03-10 13:50:02
【问题描述】:

下面的代码从数据库中获取一个 url 和 article_id。它抓取 url 页面,获取 url 中存在的图像快照并将其保存在我的远程服务器中。

PS:javascript 的菜鸟!

(async () => {
client.query("SELECT DISTINCT url,article_id FROM public.content_paraarticle",(err,res,fields)=>{
if (err)  throw err;
// console.log(res)
for(var i=0;i<res.rows.length;i++)
{

// Set up browser and page.
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();
    page.setViewport({ width: 1280, height: 926 });
    var str1='.png';


    // arr.push(res[i])
    var id=(res.rows[i].article_id);
    var str=id+str1;
    console.log(str);
    var url=(res.rows[i].url);

    console.log('taken');
    await Promise.race([
    await page.goto('https://www.thehindu.com/news/cities/kozhikode/skilled-entrepreneurs-centres-in-35-panchayats-in-kozhikode/article29434054.ece?utm_source=udmprecommendation_other-states&utm_medium=sticky_footer&transactionId=5abd798d30a44245b32a3fde2925c44d', {waitUntil: 'load'}),
    new Promise(x => setTimeout(x, 60000)),
    ]);

    const Image = await page.$('body > div.container-main > div.jscroll > div > div > div > section > div > div > div > div:nth-child(2) > div.lead-img-cont > div > picture > img');
    console.log('screenshot started to get taken');
    const shot=await Image.screenshot({
    path: str,
    omitBackground: true,
    });
    console.log('screenshot taken');
    await browser.close();



}
client.end()
});

})();

【问题讨论】:

    标签: javascript postgresql async-await web-crawler


    【解决方案1】:

    您已将一个函数传递给client.query,并且您的等待调用在该函数中,因此您需要使该函数异步。

     client.query("SELECT DISTINCT url,article_id FROM public.content_paraarticle", 
                   async (err,res,fields) => {
                   // your await calls 
                  }
    

    【讨论】:

    • 但是对于某些 url,puppeteer 会抓取并保存图像,而对于某些 url,它会抛出称为“未处理的承诺拒绝”的错误 ...想知道为什么?
    • 您的某些异步调用可能会失败,因此我建议您将代码保存在 try-catch 块中并进行处理。
    猜你喜欢
    • 2020-10-03
    • 2020-04-20
    • 2021-03-17
    • 2020-05-26
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 2022-06-18
    • 2020-03-31
    相关资源
    最近更新 更多