Skip to content

Instantly share code, notes, and snippets.

@jeremy-code
Last active June 2, 2025 08:22
Show Gist options
  • Save jeremy-code/88cbf4e4f78d34c900cb5fffd4193813 to your computer and use it in GitHub Desktop.
Save jeremy-code/88cbf4e4f78d34c900cb5fffd4193813 to your computer and use it in GitHub Desktop.
Promises resolve to the same value

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));
@jeremy-code
Copy link
Author

If this sounds obvious, let it be known that GitHub Copilot on GPT-4.1 does not know this:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment