简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM