【问题标题】:Get result from listener async从监听器异步获取结果
【发布时间】:2020-11-06 01:49:25
【问题描述】:

我使用 puppeteer-cluster + node js。我是新来的。 我有一些麻烦。 我需要从站点获取 XHR 响应。我正在收听页面,但我无法将结果值写入变量。我需要在代码的另一部分使用该值。 如何在监听器中等待函数执行并将结果写入变量?

dataCreation = [];
function get_data (data){
 dataCreation [id] = data;}
await page.on('response', async (response) =>{
  if (response.url === 'your_url'){ 
    let XHR_response = await response.json();
    let array_lenght = (XHR_response).length;
    let data2 = XHR_response.objects[array_lenght-1].creationDate;
    get_data(data2);}});

await console.log(dataCreation [id];

但是 dataCreation [id] 是不败的。因为我需要等待听众并从中获得结果。我该怎么做?谢谢。

【问题讨论】:

  • await console.log(dataCreation [id]; 的语法无效是怎么回事?
  • 抱歉,我的鳕鱼中有 )。我只在这里犯了错误,然后在stackoverflow中发布。谢谢
  • Edit 你的问题。你的问题应该有一个minimal reproducible example

标签: node.js async-await puppeteer eventemitter puppeteer-cluster


【解决方案1】:

类似这样的:

    const XHR_response = await new Promise((resolve) => {
      page.on('response', checkResponse);

      function checkResponse(response) {
        if (response.url() === 'your_url') {
          page.off('response', checkResponse);
          resolve(response.json());
        }
      }
    });

    let array_lenght = XHR_response.objects.length;
    let data2 = XHR_response.objects[array_lenght-1].creationDate;
    get_data(data2);

    console.log(dataCreation[id]);

【讨论】:

  • 是的,抱歉,打错了)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-19
  • 2011-07-09
  • 1970-01-01
  • 2013-12-27
  • 2015-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多