[英]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)
时:
console.log
first to pass its return value into resolve
;首先调用console.log
将其返回值传递给resolve
;resolve
to pass it's value into setTimeout
;调用resolve
将其值传递给setTimeout
;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.