The Novice
The Novice

Reputation: 144

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

    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"?

Upvotes: 1

Views: 474

Answers (2)

Nisanth Reddy
Nisanth Reddy

Reputation: 6405

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

Upvotes: 1

Rashed Rahat
Rashed Rahat

Reputation: 2475

Try:

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

Upvotes: 1

Related Questions