简体   繁体   English

从 async/await function 内部返回 async/await function (Puppeteer)

[英]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.我在不同的地方尝试了许多 await 配置,但无法正常工作。 Why does this return Promise { <pending> } and not "Text on page found" ?为什么这会返回Promise { <pending> }而不是"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.所以, puppeteer.launch({ headless: true })实际上会返回一个Promise ,这就是为什么你可以附加一个.then到它。

Now inside the .then , whatever you return is still going to be finally wrapped inside a Promise and returned to you.现在在.then中,无论您返回什么,最终都将被包裹在Promise并返回给您。

There are two ways to go ahead. go 前面有两种方法。

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.由于您的main function 的返回值是Promise您可以在then回调中读取它包含的值。

Other way to handle this would be to use async await again.处理此问题的其他方法是再次使用async await 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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