await仅在异步功能中有效-异步中的eval

await仅在异步功能中有效-异步中的eval

问题描述:

我想在异步函数中对某些代码行进行eval().可以使用以下代码,

I want to eval() some lines of code inside of async function. While the following code is ok,

async function foo()
{
  await foo1();
  await foo2();
}

以下内容引发错误:等待仅在异步函数中有效

the following throws an error: await is only valid in async function

let ctxScript = 'await foo1(); await foo2();';
async function foo()
{
  eval( ctxScript );
}

我该如何处理? 我的foo()应该是异步的,因为它是Puppetteer控制器函数

How could I handle this? My foo() should be async as it is Puppetteer controller function

foo()不必一定是async,因为这对eval的执行上下文没有影响.相反,一种可能的解决方案是将ctxScript包装在一个自执行的异步函数中,如下所示:eval("(async () => {" + ctxScript + "})()")

foo() should not necessarily be async, as that has no effect on the execution context of eval. Instead, a possible solution is to wrap your ctxScript in a self-executing async function, like so: eval("(async () => {" + ctxScript + "})()")