await仅在异步功能中有效-异步中的eval [英] await is only valid in async function - eval in async

查看:600
本文介绍了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 + "})()")

这篇关于await仅在异步功能中有效-异步中的eval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆