Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tbranyen
Last active February 14, 2018 17:55
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 tbranyen/5b5e263fa3c049d5fcd2f6037b254d34 to your computer and use it in GitHub Desktop.
Save tbranyen/5b5e263fa3c049d5fcd2f6037b254d34 to your computer and use it in GitHub Desktop.

Functions rescue us in this case because functions are lazy. But now, we can’t chain these things with .then() anymore.

function lazyPromise() {
  return new Promise(resolve => setTimeout(resolve, 1000))
    .then(() => console.log('Chain off all'));
}
// The only location you can't chain off is the function

// Chains just fine this way
lazyPromise().then(() => console.log('Chain off one'));
lazyPromise().then(() => console.log('Chain off two'));
const getUserAge = () => betterFetch('https://my.api.lol/user/295712')
  .then(res => res.json())
  .then(user => user.age);

And then to use this thing, we would call getUserAge.run(cb). Call run multiple times and you will invoke multiple different executions of that chain of eventual values. Yay! Reusable but still chainable.

How is this any different from what is shown below?

// Lazy and chainable
getUserAge().then(age => {});
getUserAge().then(age => {});

The post references chainability many times and I'm still confused as to when you are not able to chain using a Promise getter.

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