Skip to content

Instantly share code, notes, and snippets.

@domenic
Last active July 4, 2020 09:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save domenic/70df41c0b2e89712b3eb to your computer and use it in GitHub Desktop.
Save domenic/70df41c0b2e89712b3eb to your computer and use it in GitHub Desktop.
Avoiding explicit promise construction antipattern
function getUserDetail(username) {
if (userCache[username]) {
return Promise.resolve(userCache[username]);
}
// Use the fetch API to get the information
return fetch('users/' + username + '.json')
.then(function(result) {
userCache[username] = result;
return result;
})
.catch(function() {
throw new Error('Could not find user: ' + username);
});
}
@justsml
Copy link

justsml commented Feb 4, 2016

Hey @domenic - Nice example of fetch - a really badly needed (native) Browser API.

I was curious to know your thoughts on @isaacs Promise-hatefest this month and my comment detailing Promise-based solutions.

Here's the sample code https://gist.github.com/justsml/0afefe73da112df90dae

Thanks!!

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