Last active
October 2, 2016 09:50
-
-
Save softwarespot/a5c12cdea00d639e67ee1392da1f8054 to your computer and use it in GitHub Desktop.
The good/bad promise examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Idea 1: http://www.datchley.name/promise-patterns-anti-patterns/ | |
// good | |
good(); | |
function good() { | |
// getJSON returns a promise, so just continue the chain | |
return getJSON() | |
.then(function (artists) { | |
// Map the array of artists to an array of names | |
return artists.map(function (artist) { | |
return artist.name; | |
}); | |
}) | |
.then(function (names) { | |
// This could have been in the "thenable" before, but | |
// it's best functions only do one thing and do it well | |
console.log('(good) The promise was resolved::', names); | |
}) | |
.catch(function (err) { | |
console.log('(good) The promise was rejected::', err); | |
}) | |
} | |
// bad | |
bad(); | |
function bad() { | |
// Create a new promise and resolve/reject when | |
// the getJSON is resolved or rejected | |
return new Promise(function (resolve, reject) { | |
getJSON() | |
.then(function (artists) { | |
// Map the array of artists to an array of names | |
var names = artists.map(function (artist) { | |
return artist.name; | |
}); | |
// The "thenable" is doing too much | |
resolve(names); | |
console.log('(bad) The promise was resolved::', names); | |
}) | |
.catch(function (err) { | |
reject(err) | |
console.log('(bad) The promise was rejected::', err); | |
}); | |
}); | |
} | |
// A wrapper that returns a promise which is | |
// resolved with an array of artist objects. Lets assume | |
// that this might also throw an error (even though it doesn't') | |
function getJSON() { | |
return Promise.resolve([{ | |
id: 1, | |
name: 'Jay-Z' | |
}, { | |
id: 2, | |
name: 'Kanye West' | |
}, { | |
id: 3, | |
name: 'Meshuggah' | |
}]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment