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.