0

Why is resolve not defined through closure inside of myFunction in the code below?

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

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

(node:1232) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: resolve is not defined
evianpring
  • 3,316
  • 1
  • 25
  • 54
  • 2
    `resolve` is defined in a scope. `myFunction` is not defined in that scope. Nothing particular to promises here; this is how scope works all the time. – Ry- Jul 01 '17 at 23:20
  • 2
    Do you know of a programming language where that *would* work? – Pointy Jul 01 '17 at 23:21
  • Possible duplicate of [Resolve Javascript Promise outside function scope](https://stackoverflow.com/questions/26150232/resolve-javascript-promise-outside-function-scope) – Emeka Obianom Jul 01 '17 at 23:29

1 Answers1

4

Because that's just not how scoping works in 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:

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

const p = new Promise((resolve) => {
  myFunction(resolve);
})
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Yes, I know about lexical scoping, and I missed the fact that myFunction2 is defined outside of myFunction, so it doesn't matter where it is called. Clarified now. – evianpring Jul 02 '17 at 00:24