The title kind of sounds like gibberish but wait let me explain.
const main = async () => {
const promise1 = Promise.resolve(Math.round(Math.random() * 100));
const promise2 = promise1.then((value1) => value1 + 1);
const [value1, value2] = await Promise.all([promise1, promise2]);
// Value 1: 49, Value 2: 50
console.log(`Value 1: ${value1}, Value 2: ${value2}`);
};
const main2 = async () => {
const promise1 = Promise.resolve({});
const promise2 = promise1.then((value1) => {
value1.property2 = 2;
return value1;
});
const [value1, value2] = await Promise.all([promise1, promise2]);
// Value 1 {"property2":2}, Value 2: {"property2":2}
console.log(
`Value 1 ${JSON.stringify(value1)}, Value 2: ${JSON.stringify(value2)}`,
);
// Value 1 === Value 2: true
console.log(`Value 1 === Value 2: ${value1 === value2}`);
};
main();
main2();
node index.js
Value 1: 56, Value 2: 57
Value 1 {"property2":2}, Value 2: {"property2":2}
Value 1 === Value 2: true
Another way of putting is that when a function returns a promise, the awaited value for that promise will be the same (by reference) even if it comes from .then
or from await
.
EDIT: Also this works even if instead of using Promise.resolve you use
new Promise((resolve) => resolve(value));
If this sounds obvious, let it be known that GitHub Copilot on GPT-4.1 does not know this: