【问题标题】:How to return a value (object) from inside a puppeteer async function? [duplicate]如何从 puppeteer 异步函数内部返回值(对象)? [复制]
【发布时间】:2019-12-25 19:17:22
【问题描述】:

我正在使用 puppeteer 库进行一些网络抓取。我想将一个异步对象返回给调用它的外部函数,以便我可以将它插入到我的数据库中。

问题是,为了处理异步函数正在操作的浏览器对象,你必须调用“await browser.close();”作为最后一个电话。

另一个问题是,控制台记录我的函数的结果只显示一个承诺。

我尝试在 await browser.close() 方法之后放置 return 语句,以及放置“return await mainObj”,但它仍然返回一个 Promise。

const puppeteer = require('puppeteer');

async function webScraper(u, p, url) {
    const browser = await puppeteer.launch();

    const page = await browser.newPage();



    await page.goto(url);
    await page.waitForSelector('#UserName')
    await page.focus('#UserName')
    await page.keyboard.type(u)
    await page.waitForSelector('#Password')
    await page.focus('#Password')
    await page.keyboard.type(p)

    // Code edited out to keep private what website I'm using.
    // Here it loops through page contents and constructs arrays which are used to construct my mainObj.

    let mainObj = {};
    let secondObj = {};

    for (i = 0; i < descArray.length; i++) {

        secondObj[descArray[i]] = [ammtArray[i], datesArray[i]]

    }
    secondObj[totaldescArray[0]] = totalammtArray[0]
    mainObj[datesArray[0]] = secondObj


    console.log(mainObj, 'here')

    await browser.close();

    return await mainObj

}
console.log(webScraper("username", "password", "url"))

Console.logging 函数中的 mainObj 返回我预期的对象。但是 console.logging 调用函数 webScraper() 的结果会返回一个 Promise。我是否使用“return await mainObj”或“return mainObj”(请记住该对象已等待,因为构造数组的省略部分是异步的)。

有人可以指出我做错了什么吗?谢谢。

【问题讨论】:

    标签: javascript asynchronous async-await return puppeteer


    【解决方案1】:

    也许您应该等待从webScraper 返回的承诺完成处理。由于您不能在async 函数之外使用await,因此请使用Promise.then

    webScraper("username", "password", "url")
         .then(mainObj => console.log(mainObj));
    

    【讨论】:

    • 这行得通,我认为这与我调用和接收结果的方式有关。我对异步还是很陌生......所以非常感谢你提供的知识。我会标记这是尽快回答(并给你 10k 声望!)
    • 10k 它是!谢谢@威尔! :)
    猜你喜欢
    • 2016-01-14
    • 2018-07-09
    相关资源
    最近更新 更多