繁体   English   中英

为什么不能通过在promise中调用的函数内部的闭包来定义解析?

[英]Why is resolve not defined through closure inside a function called in a promise?

为什么在下面的代码中未通过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

因为这不是范围定义在JavaScript中的工作方式。 范围界定是一个词汇问题,这意味着重要的不是调用/被调用环境之间的动态关系,而是代码的结构和声明的嵌套。

您当然可以明确地将resolve函数引用传递给另一个函数:

const myFunction = (resolve) => {
  resolve();
}

const p = new Promise((resolve) => {
  myFunction(resolve);
})

暂无
暂无

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

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