【发布时间】: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