Skip to content

Instantly share code, notes, and snippets.

@James-Firth
Last active October 6, 2021 16:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save James-Firth/97e4f624303d42686257be7e13773116 to your computer and use it in GitHub Desktop.
Save James-Firth/97e4f624303d42686257be7e13773116 to your computer and use it in GitHub Desktop.
Why you need to re-assign promises
// Expected (and actual) output:
// "first done"
// "hello world!"
let reassigned = Promise.resolve();
reassigned = reassigned.then(() => new Promise((resolve, reject) => { setTimeout(() => {console.log('first done'); return resolve("hello")}, 3000);}) );
reassigned.then((x) => new Promise((resolve, reject) => { console.log(`${x} world!`); resolve(`${x} world!`);}));
// Expected output:
// "first done"
// "hello world!"
// Actual output:
// "undefined world!"
// "first done"
let separate = Promise.resolve();
separate.then(() => new Promise((resolve, reject) => { setTimeout(() => {console.log('first done'); return resolve("hello")}, 3000);}) );
separate.then((x) => new Promise((resolve, reject) => { console.log(`${x} world!`); resolve(`${x} world!`);}));

This is an example of why you need to re-assign promises in a chain to keep the chain in order. They've been given different variables so you can copy & paste both examples into the same terminal.

Note: You'll need to hit <ENTER> again quickly to see the results properly.

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