简体   繁体   中英

proper way to convert promise with resolve & reject to async function (puppeteer)

so im new to async functions and promises , imagine a promiselike this (pleas ignore syntax errors)

await new Promise(async (resolve, reject ) => {
    const page = await browser.newPage();

    await page.goto('https://example.com').catch( ()=>reject('ERROR -> LINK 1 TIMEOUT '));
    // INSERT USERNAME AND PASSWORD 
    await page.$eval('form', form => form.submit()).catch( ()=>reject('ERROR -> FORM SUBMIT ERROR '));

        if( await page.$("#username"))
        {

            reject(" ERROR -> LOGIN FAILED !!!!!!!!!!!!!! ");
        }




    await page.waitForSelector('#xxx').catch( ()=>reject('ERROR -> WAITING FOR ELEMENT TIMEOUT '));

    var scraped_data = // dop some page evaluate and scrap data;

    resolve(scraped_data);

}).then(function(scraped_data){

    await page.close();
    console.log('all done');
    insert_data_in_databas(scraped_data);

})
.catch(function(error){

    console.log(' tab failed : ');
    console.log(error);
});

i want to convert this to a async function ... what is proper way to do this ? should i just put all of them in a try/catch block like

async function do_stuff(){

    try {
        const page    = await browser.newPage();
        await page.setViewport({ width: 1000, height: 1100});
        await page.goto( 'https://example.com'  );
        // INSERT USERNAME AND PASSWORD 
        await page.$eval('form', form => form.submit());
        await page.waitForSelector('#xxx');
        var scraped_data = // dop some page evaluate and scrap data;
        await page.close();
        console.log('all done');
        insert_data_in_databas(scraped_data);    
    }
    catch (e) {
        await page.close();
        console.log('error');
        console.log(e);
    }
}

how can i reject when there is a error so the rest of the code wouldnt execute ? can i have custom error text in catche block like

ERROR -> FORM SUBMIT ERROR 

how should i to this

  if( await page.$("#username"))
        {

            reject(" ERROR -> LOGIN FAILED !!!!!!!!!!!!!! ");
        }

which is not an actual error (i mean its not code error) in try/catche ?

------------------------------------------ edit --------------------

i tried

async function open_tab(){

    try {
        const page    = await browser.newPage();
        await page.setViewport({ width: 1000, height: 1100});
        await page.goto( 'https://google.com'  );
        await page.waitForSelector('#xxx').catch(()=> { throw new Error('ERROR -> LOGIN FAILED')});
        await page.close();
        console.log('all done');
    }
    catch (e) {
        console.log('error');
        console.log(e);
        await page.close();

    }
}

its almost working but i cant close the tab in the catch block i get

UnhandledPromiseRejectionWarning: ReferenceError: page is not defined

and the tab remains open which is not ideal

There should be no new Promise because a promise already exists and can be chained.

If resulting promise should be rejected in async function, it is:

if (await page.$("#username")) {
   throw new Error('ERROR -> LOGIN FAILED');
}

It should be

let page;
try {
    page    = await browser.newPage();

instead of

try {
    const page    = await browser.newPage();

// Best solution for error handling in puppeteer

const puppeteer = require("puppeteer");
const param_puppeteer = {
  args: [
    "--incognito",
    "--ignore-certificate-errors",
    "--no-sandbox",
    "--disable-setuid-sandbox",
    "--window-size=1920,1080",
    "--disable-accelerated-2d-canvas",
    "--disable-gpu",

    // '--unlimited-storage',
    // '--no-startup-window',
    // '--disable-dev-shm-usage',
    // '--disable-crash-reporter',
    // '--disable-breakpad'
  ],
  headless: false,
};

async function start() {
  return puppeteer
    .launch(param_puppeteer)
    .then(async (browser) => {
      const page = await browser.newPage();
      return await task(page)
        .catch((err) => console.log(err))
        .finally(() => browser.close());
    })
    .catch((err) => console.log(err));
}

async function task(page) {
  await page.setViewport({ width: 1000, height: 1100 });
  await page.goto("https://google.com");
  await page.waitForSelector("#hplogo");
  let exist = await page.$("#hplogo").then((res) => !!res);
  if (exist) {
    return new Promise((resolve, reject) => resolve("success"));
  } else {
    return new Promise((resolve, reject) => reject("failed"));
  }
}

start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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