在Puppeteer中使用Partial

时间:2018-05-15 23:10:55

标签: javascript reactjs functional-programming async-await puppeteer

我正在努力重构我的puppeteer代码,以重复使用部分格式的重复代码。我有多个项目将重复选择器变量旁边相同的4行。请参阅下面4行的示例。

我希望能够将ACHIEVEMENTS.community_ask_question_id传递给可重复的功能。有没有人有任何想法?

await page.waitForSelector(ACHIEVEMENTS.community_ask_question_id);  
await page.click(ACHIEVEMENTS.community_ask_question_id,{delay: 500}); 
await page.click(COMPLETE_ACHIEVEMENT, {delay: 500}); 
await page.click(CONFIRM_COMPLETE, {delay: 500});

1 个答案:

答案 0 :(得分:0)

您确实可以创建一个单独的函数,只需确保它是一个async

async function clicker(page, ACHIEVEMENTS) {
  await page.waitForSelector(ACHIEVEMENTS.community_ask_question_id);  
  await page.click(ACHIEVEMENTS.community_ask_question_id,{delay: 500}); 
  await page.click(ACHIEVEMENTS.COMPLETE_ACHIEVEMENT, {delay: 500}); 
  await page.click(ACHIEVEMENTS.CONFIRM_COMPLETE, {delay: 500});
}

(async() => {

  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  /// ...
  for(var i in ACHIEVEMENTS) {
    await clicker(page, ACHIEVEMENTS[i]);
  }
})()