如何从操纵up异步函数内部返回值(对象)?

时间:2019-08-20 14:28:00

标签: javascript asynchronous async-await return puppeteer

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

问题是,为了处置异步功能正在运行的浏览器对象,您必须调用“ await browser.close();”。作为最后一个电话。

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

我尝试将return语句放在我的await browser.close()方法之后,以及将“ 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.loging函数中的mainObj返回我期望的对象。但是console.logging调用函数webScraper()的结果将返回Promise。我是否使用“ return await mainObj”或“ return mainObj”(请注意,对象等待,因为构造数组的省略部分是异步的)。

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

1 个答案:

答案 0 :(得分:2)

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

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