[英]can you await a function not defined as async but declared new Promise inside of it?
[英]code shows error await can only be declared inside async function although there is async function
下面的代碼從數據庫中獲取 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()
});
})();
您已將 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.