Home > Enterprise >  how is this thenable able to refer its own self
how is this thenable able to refer its own self

Time:02-03

I have this one line of code but I cant seem to understand how this works

let p1 = p.then(a => [p1])
let [p2] = await p1
console.log(p1===p2)

I cant understand the first line. how can then get a hold of p1. afaik, a => [p1] inside then is executed immediately, but at the time of execution ,surely p1 was not formed yet. so, how come that code work? not only that, it somehow manages to correctly refer to itself. can anybody help understand what's going on here?

thanks

CodePudding user response:

a => [p1] inside then is executed immediately

No, it's not. A .then called on a fulfilled Promise does not get called immediately. p1 is initialized and the Promise is assigned to it before the .then callback runs, so there's no problem.

This should make it clearer:

(async () => {
  const p = Promise.resolve();
  console.log('starting');
  let p1 = p.then(a => {
    console.log('then running');
    return [p1];
  });
  console.log('p1 has now been initialized');
  let [p2] = await p1;
  console.log(p1===p2);
})();

If it was executed immediately, you'd be correct - p1 hasn't been initialized yet at the point that it's being referenced, and an error would be thrown.

(async () => {
  const someObjectWhoseThenRunsImmediately = {
    then: (callback) => {
      // do something with callback, synchronously...
      callback();
    }
  };
  console.log('starting');
  let p1 = someObjectWhoseThenRunsImmediately.then(a => {
    console.log('then running');
    return [p1];
  });
  console.log('p1 has now been initialized');
  let [p2] = await p1;
  console.log(p1===p2);
})();

But that's not how Promises work.

  • Related