正确的方法来将带有解析和拒绝的承诺转换为异步功能(伪造者)

时间:2018-10-05 18:56:23

标签: javascript node.js promise puppeteer

对于异步函数和promise来说是新手,请想象一下这样的promise(请忽略语法错误)

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);
});

我想将其转换为异步函数...执行此操作的正确方法是什么?我应该把它们都放在

这样的try / catch块中吗
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);
    }
}

当出现错误时我如何拒绝,以便其余代码无法执行?我可以在

这样的catche块中添加自定义错误文本吗
ERROR -> FORM SUBMIT ERROR 

我应该怎么做

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

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

这不是try / catche中的实际错误(不是代码错误)?

------------------------------------------编辑---- ----------------

我尝试过

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();

    }
}

它几乎可以正常工作,但是我无法关闭获得的catch块中的标签

UnhandledPromiseRejectionWarning: ReferenceError: page is not defined

并且选项卡保持打开状态,这不理想

2 个答案:

答案 0 :(得分:0)

不应有new Promise,因为一个承诺已经存在并且可以被链接。

如果应在async函数中拒绝产生的承诺,则为:

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

应该是

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

代替

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

答案 1 :(得分:0)

//在伪娘中处理错误的最佳解决方案

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();