简体   繁体   English

代码显示错误 await 只能在异步 function 中声明,尽管存在异步 function

[英]code shows error await can only be declared inside async function although there is async function

The code below fetches a url and article_id from the database.下面的代码从数据库中获取 url 和 article_id。 It crawls the url page, takes the snaps of images present in the url and saves it in my remote server.它爬取 url 页面,拍摄 url 中存在的图像快照并将其保存在我的远程服务器中。

PS: Noob at javascript! 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()
});

})();

You have passed a function to client.query and your await calls are in that function, so you need to make that function async.您已将 function 传递给client.query ,并且您的等待调用在 function 中,因此您需要使 function 异步。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM