Skip to content

Instantly share code, notes, and snippets.

Forked from domenic/not-bad-code.js
Last active February 4, 2016 02:15
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save justsml/0afefe73da112df90dae to your computer and use it in GitHub Desktop.
Avoiding explicit promise construction antipattern. Added bluebird.js secret sauce.
// Promises are great, but bluebird covers :allthethings
var Promise = require('bluebird');
var appContext = {ready: false, error: false};
const INVALID_CTX = {ready: false, error: true, message: 'App or User not initialized'};
// Bluebird-ify around `fetch` API
function getUser(username) {return Promise.resolve('users/' + username + '.json').then(fetch);}
function initApp(username) {
// Use bluebird to do some real-world-ish code:
// First, get a user, cache them, check an inbox, then filter msgs already viewed
return getUser(username)
.timeout(2500) // easy to declare expected performance, seriously awesome
.bind(appContext) // subsequent Promise methods can share access to appContext obj via `this`
.tap(user => this.user = user) // use `.tap` to cache the result without modifying the promise result/chain
.then(checkInbox) // send the returned `user` to `checkInbox` - returns an array of msgs
.tap(messages => this.messages = messages.length) // cache the # of msgs for UI
.filter(msg => !msg.viewed) // applied to current array excludes previously viewed msgs
.tap(unreadMsgs => {
// update UI without changing promise's return value
if (unreadMsgs.length >= 1) {
showToast(`${unreadMsgs.length} New Messages: ${unreadMsgs[0].subject}...`);
} else {
showToast('No new messages');
.tap(() => this.ready = true) // at the end of the line, set `ready` flag
.then(checkContext) // return the app's context for further chaining
.catch(console.error.bind(console, `Err! not very fetching: ${url}`))
function checkContext() {
if ( !this.user || !this.messages ) {
// uh oh, override context
// otherwise ok, return ctx
return this;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment