Return from async/await function inside async/await function (Puppeteer)

Viewed 172
    let hi = main("1404339566");
    console.log(hi)    

    function main(isbn) {
      return puppeteer.launch({ headless: true  }).then(async browser => {
          return "Text on page found";
      })
    }

I am trying to get this to print "Text on page found". I have tried many configurations of await in different places but can't get it working. Why does this return Promise { <pending> } and not "Text on page found"?

2 Answers

So, puppeteer.launch({ headless: true }) actually returns you a Promise, thats why you are able to attach a .then to it.

Now inside the .then, whatever you return is still going to be finally wrapped inside a Promise and returned to you.

There are two ways to go ahead.

One way you can solve this is,

main("1404339566").then(value => console.log(value);

function main(isbn) {
  return puppeteer.launch({ headless: true  }).then(async browser => {
      return "Text on page found";
  })
}

Since the return value of your main function is a Promise you can read the value it contains inside a then callback.

Other way to handle this would be to use async await again. Like this. This code might or might not change slightly depending on your actual use case.

function main(isbn) {
  return puppeteer.launch({ headless: true  }).then(async browser => {
      return "Text on page found";
  })
}

console.log(await main("1404339566"));

Try:

main("1404339566").then(res => console.log(res);
Related