0

I'm just experimenting and came across this:

    var d = 7;
    var p1 = new Promise((a, b) => { 
        console.log(p1);
        console.log(d);
        a('whatever');
    });

I'm just curious about what's going on here. The fact that I'm really sure this gonna work, but doesnt, means there's a gap in my understanding. could anyone explain why p1 is not reachable from inside a, but d is? workaround is easy, but I just want to understand this one.

Thanks.

Das Raf
  • 55
  • 6
  • 7
    You're logging `p1` before it is assigned. That's really it. – VLAZ Jan 29 '23 at 20:25
  • 4
    Assignment happens from right to left. The Promise constructor executes its executor immediately. Does this help? – Sebastian Simon Jan 29 '23 at 20:25
  • 3
    [When is the body of a Promise executed?](https://stackoverflow.com/q/42118900) – VLAZ Jan 29 '23 at 20:26
  • 1
    dang, how can I overlook this simple fact...yeah you guys are right...guess this is what happens when you're too focused on API and lose sight of the basic of basics...thanks all – Das Raf Jan 29 '23 at 20:27
  • 2
    Related: [Javascript: Access Promise object from within function passed to Promise constructor](/q/48289911/4642212). – Sebastian Simon Jan 29 '23 at 20:28
  • You can confirm the order of things with the [specification](//tc39.es/ecma262/#sec-promise-executor). Also, consider `const p1 = Promise.resolve().then(() => { console.log(p1); return "whatever"; });`, which requires one pass through the job queue, before calling the `then` callback. – Sebastian Simon Jan 29 '23 at 21:00

0 Answers0