在 puppeter 脚本的 page.evaluate 的 return 块中使用箭头函数

using arrow function into the return block of page.evaluate of puppeter script

大概是Promise的问题:

看看我的 return 块的 since 字段, 使用箭头函数它不会 return 任何结果:

{
    link: 'www.xxxxxx.com/1234',
    name: 'jhon doe',
    since: {}
},

而不是直接return值,它按预期工作!

由于我需要使用选择器执行复杂的操作,所以我想在这一点上使用内联箭头函数,我该如何解决才能得到结果?

  let rawMembers = await page.evaluate(() => new Promise((resolve) => { 
    
    ....
    //captute all the link
    const anchors = Array.from(document.querySelectorAll('a'));
    let result = anchors.map(x =>  {  
          return {
            link: x.getAttribute("href"),
            name: x.innerText,
            //since : x.parentNode.parentNode.parentNode.parentNode.getAttribute("class")   <--- this works
            since:  x => {                                                                  <---using an arrow function, it returns and empty objecy `{}`
                // i need a function here to do complex and multiline operations
                return x.parentNode.parentNode.parentNode.parentNode.getAttribute("class");
            }
        

    ....
    resolve(results);

我也试过了,结果一样

since:  x => new Promise((resolve) => {
                // i need a function here to do complex and multiline operations
                resolve(x.parentNode.parentNode.parentNode.parentNode.getAttribute("class"));
            })

since 中,您引用了箭头函数本身,而不是其结果。函数不可序列化,所以你得到一个空对象。您需要调用该函数,即使用 IIFE:

since: (() => {
  return x.parentNode.parentNode.parentNode.parentNode.getAttribute("class");
})()