puppeteer用回调评估功能

Bla*_*son 3 puppeteer

我试图用puppeteer评估一个函数,但回调永远不会被触发(我确定主页正在按预期工作).

在主机页面上,监听器的工作方式如下:

DB.when('ready').execute(function(db){
  // DB can execute stuff
})
Run Code Online (Sandbox Code Playgroud)

我的puppeteer代码尝试获取准备好的数据库:

try {
  const dbhandle = await page.evaluate('DB.when("ready")');
  const result = await page.evaluate(db => db.execute, function(images) {
    console.log(JSON.stringify(images));
    //do stuff with callback
  }, dbhandle);
    console.log('result', JSON.stringify(result));
} catch (e) {
    console.log('evaluate', e);
} finally {
    console.log('finally');
}
Run Code Online (Sandbox Code Playgroud)

我没有运气.

Bla*_*son 6

天哪,我明白了......

try {
  function fooBugger() {
    return new Promise((resolve, reject) => {
      DB.when('ready').execute(function(db) {
        if (db) {
          resolve(db.some_data);
        } else {
          reject('nope');
        }
      });
    });
  }
  const res = await page.evaluate(fooBugger);

  console.log('resultHandle', JSON.stringify(res));
} catch (e) {
  console.log('evaluateHandle', e);
} finally {
}
Run Code Online (Sandbox Code Playgroud)

  • 干得好!大多数东西都是以承诺为基础的,所以包含带有承诺的回调通常是要走的路. (2认同)