javascript - 如何从 puppeteer 异步函数内部返回值(对象)?

标签 javascript asynchronous async-await return puppeteer

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

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

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

我尝试将 return 语句放在 wait browser.close() 方法之后,以及放置“return wait 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 wait mainObj”或“return mainObj”(请记住,等待对象是因为构造数组的省略部分是异步的)。

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

最佳答案

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

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

关于javascript - 如何从 puppeteer 异步函数内部返回值(对象)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57575889/

相关文章:

javascript - 如何将 td 元素附加到表中 th 元素的同一列中?

java - 使顺序处理异步,而不使用 "parallel"运算符

javascript - 如何中断或取消 promise 以清理在 JavaScript/TypeScript 中异步创建的多个对象

C# async/await - 多项任务首选一项

c# - 使用 Task.Delay() 的循环是否会造成内存泄漏?

c# - 为什么这个 async/await 代码会生成 "...not all code paths return a value"?

javascript - Chrome 扩展和 javascript 提交表单

javascript - 如何在IE中更改src后获取新的图像大小

javascript - 带前导零的整数的 Bootstrap 验证

c - 使用 Windows slim 读/写锁