简体   繁体   English

MDN 上的澄清“使用函数而不是评估代码片段”——为什么?

[英]Clarifications on MDN "Use functions instead of evaluating snippets of code" - why's that?

On MDN article about eval there's a paragraph titled Use functions instead of evaluating snippets of code , in the example code there's a reference about setTimeout().在关于eval的 MDN 文章中有一段标题为使用函数而不是评估代码片段,在示例代码中有一个关于 setTimeout() 的参考。 I can't grasp why this advice/command, so, keeping the setTimeout() reference, could someone point me out why these codes work as expected:我无法理解为什么这个建议/命令,所以,保留 setTimeout() 参考,有人可以指出为什么这些代码按预期工作:

function timedPromise(){
  return new Promise((resolve) => {
    setTimeout(( ) => {resolve(console.log('Promise resolved!'))}, 1000)
  })
};
 
function timedPromise2(){
  return new Promise((resolve) => {
    setTimeout(function(){resolve(console.log('Another promise resolved!'))}, 2000)
  })
};
timedPromise();
timedPromise2();
/*output:
Promise {<pending>}
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined
Promise resolved! //after at least 1s
Another promise resolved! //after at least 2s
*/

While this code won't?虽然这段代码不会?

function timedPromise(){
  return new Promise((resolve) => {
    setTimeout(resolve(console.log('I resolved!')), 1000)
  })
};
 
timedPromise();
/*output:
I resolved! //immediate
Promise {<fulfilled>: undefined}
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined
*/

I understand the browser evaluates the code snippet as a string instead of a function, and then interprets it and executes it immediately instead of waiting for the delay of setTimeout() to pass.我了解浏览器将代码片段评估为string而不是 function,然后对其进行解释并立即执行它,而不是等待 setTimeout() 的延迟通过。

Why though?为什么呢?

Why/when should I use wrapper functions instead of code snippets as parameters?为什么/何时应该使用包装函数而不是代码片段作为参数? Is it a thing related only to asynchronicity?它仅与异步有关吗?

When you write functionName() , the () call the function immediantly.当您编写functionName()时, ()立即调用 function。

So when you write setTimeout(resolve(console.log('I resolved,')), 1000) it:因此,当您编写setTimeout(resolve(console.log('I resolved,')), 1000)时:

  • Calls console.log first to pass its return value into resolve ;首先调用console.log将其返回值传递给resolve
  • Calls resolve to pass it's value into setTimeout ;调用resolve将其值传递给setTimeout
  • Calls setTimeout .调用setTimeout

When you wrap a function in a lambda, you're passing a reference to that function through, rather than calling it immediantly.当您将 function 包装在 lambda 中时,您传递的是对该 function 的引用,而不是立即调用它。 It might be clearer to see like this:像这样看可能更清楚:

function doLog() { console.log("Hello, world!"); }

// Calls doLog instantly, passes in return value of undefined
setTimeout(doLog(), 1000); 

// Passes in a reference to doLog, which setTimeout will then call later
setTimeout(doLog, 1000);

暂无
暂无

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

相关问题 如何使用正则表达式在 Visual Studio Code 的代码片段中“大写和替换”? - How to use Regex to 'capitalize and replace' in Visual Studio Code's snippets? 为什么当 t 类似于 MDN 时我的代码不起作用? (面向对象) - Why is my code not working when t is similar to MDN? (OOP) 为什么MDN的web worker示例中的随机密钥? - Why the random-looking keys in MDN's web worker example? 为什么使用jQuery的css()函数代替maxHeight或其他命名的CSS函数? - Why use jQuery's css() function instead of maxHeight or the other named CSS functions? 为什么该三元抛出错误而不是评估为false? - why is this ternary throwing an error instead of evaluating to false? MDN的Element.hasAttribute()代码示例令人难以理解,我希望其代码片段清晰明了 - MDN'S Example of Element.hasAttribute() code is confusing to understand, I would like clarity on its code snippet 为什么我们应该使用jQuery而不是函数直接使用匿名函数? - Why should we use anonymous functions with jQuery instead of the function directly? 如果我使用函数参数而不是固定值,为什么这会有所不同? - Why this works different if I use functions parameters instead of fixed values? 为什么MDN的`Object.create` polyfill没有设置`prototype.constructor`? - Why doesn't MDN's `Object.create` polyfill set `prototype.constructor`? 为什么使用 Yeoman 的生成器而不是 Maven 的原型? - Why use Yeoman's generators instead of Maven's archetypes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM