如何为异步功能使用Promise?

时间:2019-01-18 16:11:11

标签: javascript promise puppeteer

该异步功能如何使用promise?

当我调用异步函数时,有时会失败,并且在日志中会显示未处理的承诺。我如何在这里使用Promise?

async function getDate(param) {
    const browser = await puppeteer.launch({ headless: true });
    const page = await browser.newPage();

    const targetUrl = `http://some-site.com/summary?t= ${param} &culture=en_US`;
    await page.goto(targetUrl);

    const dateSelector = "some-css-selector";

    const dateText = await page.evaluate((sel) => {
        return document.querySelectorAll(sel)[0].innerHTML;
    }, dateSelector);

    const date = dateText.substring(6, 16);
    console.log(date);

    browser.close();
    return date;
}
//I am calling this function this way
const myDate = getDate(myParam);

编辑1: 按照建议,我添加了try / catch块,似乎可以解决错误问题。

现在,如何在.then()上使用myDate? 由于getDate()是异步函数,因此是一个承诺。承诺解决后,我想做这样的事情:

myDate.then(
        console.log(`date1`, myDate)
    )

现在它即将出现

date1 Promise { <pending> }

编辑2: 解决了

myDate.then(result => console.log(result))

1 个答案:

答案 0 :(得分:0)

使用try/catch

async function getDate(param) {
  try {
    const browser = await puppeteer.launch({ headless: true });
    const page = await browser.newPage();

    const targetUrl = `http://some-site.com/summary?t= ${param} &culture=en_US`;
    await page.goto(targetUrl);

    const dateSelector = "some-css-selector";

    const dateText = await page.evaluate((sel) => {
        return document.querySelectorAll(sel)[0].innerHTML;
    }, dateSelector);

    const date = dateText.substring(6, 16);
    console.log(date);

    browser.close();
  } catch (error) {
    console.error(error);
  }
}

详细了解here