Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
return INVALID_CTX;
}
// otherwise ok, return ctx
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.