如何在一个自称的asynchronous函数内插入一个参数?

我有一个快速安装与发布请求。 我试图添加req (async (req, res)

 router.post('/search', (req, res) => { ;(async (req, res) => { const browser = await puppeteer.launch() const page = await browser.newPage() await page.goto(`https://www.google.com/search?tbm=bks&q=%22this+is%22`) const result = await page.evaluate(() => { console.log('CLAUSESS:', req.body.clauses) const clauses = req.body.clauses return clauses.map(clause => clause.textContent) }) result.join('\n') await browser.close() res.send(result) })() }) 

但是,我仍然得到这个错误:

(节点:5757)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):错误:评估失败:ReferenceError:req未在以下位置定义:2:32

什么是这样做的正确方法?

       

网上收集的解决方案 "如何在一个自称的asynchronous函数内插入一个参数?"

你的棉绒(如果有的话)应该抱怨你在IIFE上隐藏了variables。 我会重写它

 router.post('/search', (req, res) => { ;(async () => { const browser = await puppeteer.launch() const page = await browser.newPage() await page.goto(`https://www.google.com/search?tbm=bks&q=%22this+is%22`) const result = await page.evaluate(() => { console.log('CLAUSESS:', req.body.clauses) const clauses = req.body.clauses return clauses.map(clause => clause.textContent) }) result.join('\n') await browser.close() res.send(result) })() }) 

使它使用reqres从路由器,而不是自己的阴影空虚。

您应该调用自调用函数来传递值

这一行;(async (req, res) => {就是函数定义,所以你定义了一个函数来接受reqres但是实际上并没有把这些值传递给自调函数。

检查下面的代码,我刚刚添加reqres作为参数,而调用函数这一行})(req,res);

 router.post('/search', (req, res) => { ;(async (req, res) => { //req and res here are just parameters in function definition const browser = await puppeteer.launch() const page = await browser.newPage() await page.goto(`https://www.google.com/search?tbm=bks&q=%22this+is%22`) const result = await page.evaluate(() => { console.log('CLAUSESS:', req.body.clauses) const clauses = req.body.clauses return clauses.map(clause => clause.textContent) }) result.join('\n') await browser.close() res.send(result) })(req,res); //This is where we call the function, so we need to pass the actual values here. }) 

或者在你的情况下,你可以从函数中删除参数,因为自调用函数仍然可以访问它的包含函数reqres

所以你的代码将变成:

 router.post('/search', (req, res) => { ;(async () => { //removed parameters from function definition as they are already accessible from containing function const browser = await puppeteer.launch() const page = await browser.newPage() await page.goto(`https://www.google.com/search?tbm=bks&q=%22this+is%22`) const result = await page.evaluate(() => { console.log('CLAUSESS:', req.body.clauses) const clauses = req.body.clauses return clauses.map(clause => clause.textContent) }) result.join('\n') await browser.close() res.send(result) })(); })