如何将参数传递给 NodeJS 中的异步函数?

How to pass parameters to async function in NodeJS?

我正在尝试使用软件包 puppeteer

从网站截取屏幕截图

为此我用 Express 创建了一个简单的服务器:

app.get('/requestScreenShootForDesktop/:id', function(req, res){
    (async () => {
        const pathUpload = 'uploads/' + Math.floor(Date.now() / 1000) + '.png';
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto(this.req.params.id);
        await page.setViewport({width: 1920, height: 1080});
        await page.screenshot({path: pathUpload});

        await browser.close();
        await res.send({msg: 'ScreenShot Ok'});
      })();
});

此代码的问题在线 await page.goto(this.req.params.id);,Node 说:

Cannot read property 'params' of undefined

这是因为属于函数 app.get 的变量 req 在异步作用域中不存在。

如何解决这个问题,并将我的变量传递给异步函数?

(async (req, res) => {
    const pathUpload = 'uploads/' + Math.floor(Date.now() / 1000) + '.png';
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(req.params.id);
    await page.setViewport({width: 1920, height: 1080});
    await page.screenshot({path: pathUpload});

    await browser.close();
    await res.send({msg: 'ScreenShot Ok'});
  })(req, res);

只需放弃 LIFE,不要使用 this 访问 req

app.get('/requestScreenShootForDesktop/:id', async function(req, res){
    const pathUpload = 'uploads/' + Math.floor(Date.now() / 1000) + '.png';
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    await page.goto(req.params.id);
    await page.setViewport({width: 1920, height: 1080});
    await page.screenshot({path: pathUpload});

    await browser.close();

    res.send({msg: 'ScreenShot Ok'});
});

您可以保留 IIFE,但删除 this 关键字