Search code examples
promisepuppeteerarrow-functions

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


It probably is a matter of Promise:

Look at the since field of my return block, using an arrow function it doesn't return any result:

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

instead to return directly the value, it works as expected!

Since i need to perform complex operations with selectors, I'd like to use an inline arrow function in that point, how can I fix to get the result out?

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

i've tried this as well but with the same result

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

Solution

  • In since you have a reference to the arrow function itself, not to its result. Functions are not serialaizable, so you get an empty object. You need to call the function, i.e. to use IIFE:

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