简体   繁体   English

Javascript“eval”是同步还是异步?

[英]Is Javascript “eval” synchronous or asynchronous?

Consider the following code: 请考虑以下代码:

eval(".....;a=5;b=10;");
eval("a+b");

If in case here the 1st eval runs for long time, will my next eval return an error mentioning as a and b are undefined, as the a and b values are initialised at the end of 1st eval. 如果在这种情况下,第一个eval长时间运行,我的下一个eval会返回一个错误,提到a和b是未定义的,因为a和b值是在1st eval结束时初始化的。 Will the eval method run synchronously or asynchronously eval方法是同步还是异步运行

eval is synchronous. eval是同步的。

Lets look at this example: 让我们看一下这个例子:

 console.log("before") eval("console.log('eval')"); console.log("after"); 

You can see in that the print is in the order. 您可以看到打印件在订单中。

if it was asynchronous for example in this case: 如果它是异步的,例如在这种情况下:

 console.log("before"); setTimeout(()=>console.log("asynchronous"),0) console.log("after") 

The asynchronous run after. 异步运行之后。

eval is synchronous in nature. eval本质上是同步的。 But the evaluations/expressions inside the eval may have asynchronous code like setTimeout or setInterval . 但是eval /表达式可能有异步代码,如setTimeoutsetInterval

For an instance. 例如。

Method 1 : (synchronous example) 方法1 :(同步示例)

 eval('var a=5, b=10;'); eval('console.log(a+b)'); 

Method 2 : (asynchronous example) 方法2 :(异步示例)

 eval('setInterval(function(){window["a"]=5, window["b"]=10;}, 1000)'); eval('console.log(typeof a)'); 

Note : Anyways, it's not recommended to use eval as mentioned in https://stackoverflow.com/a/86580/7055233 注意 :无论如何,不​​建议使用https://stackoverflow.com/a/86580/7055233中提到的eval

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM