[英]Why is resolve not defined through closure inside a function called in a promise?
Why is resolve
not defined through closure inside of myFunction
in the code below? 为什么在下面的代码中未通过
myFunction
内部的闭包定义resolve
?
const myFunction = () => {
resolve();
}
const p = new Promise((resolve) => {
myFunction();
}
(node:1232) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: resolve is not defined
Because that's just not how scoping works in JavaScript. 因为这不是范围定义在JavaScript中的工作方式。 Scoping is a lexical thing, meaning that what's important is not the dynamic relationship between calling/called environments but the structure of the code and the nesting of declarations.
范围界定是一个词汇问题,这意味着重要的不是调用/被调用环境之间的动态关系,而是代码的结构和声明的嵌套。
You can of course explicitly pass the resolve
function reference to the other function: 您当然可以明确地将
resolve
函数引用传递给另一个函数:
const myFunction = (resolve) => {
resolve();
}
const p = new Promise((resolve) => {
myFunction(resolve);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.