Skip to content

Instantly share code, notes, and snippets.

@lukemartin
Last active August 29, 2015 14:04
Show Gist options
  • Save lukemartin/c7ce365d6805f238020a to your computer and use it in GitHub Desktop.
Save lukemartin/c7ce365d6805f238020a to your computer and use it in GitHub Desktop.
Bluebird Promise Example
Promise = require 'bluebird'
getName = ->
return new Promise((resolve) -> resolve('Luke'))
getAge = (name) ->
data =
'Luke': 27
return new Promise((resolve, reject) ->
return resolve(data[name]) if data[name]
return reject(new Error('No matching name found.'))
)
getUser = (name, age) ->
data =
'Luke27': { name: 'Luke', age: 27, fave: 'Mew' }
return new Promise((resolve, reject) ->
return resolve(data[name+age]) if data[name+age]
return reject(new Error('No matching user found.'))
)
getName()
.then((name) ->
console.log(name)
return getAge(name).then((age) ->
console.log(age)
return getUser(name, age)
)
)
.then((user) ->
console.log(user)
)
.catch((e) ->
console.log(e)
)
var Promise = require('bluebird');
function getName() {
return new Promise(function(resolve) {
resolve('Luke');
});
}
function getAge(name) {
var data = {
'Luke': 27
};
return new Promise(function(resolve, reject) {
if(data[name]) {
return resolve(data[name]);
}
return reject(new Error('No matching person found.'));
});
}
function getUser(name, age) {
var data = {
'Luke27': {
name: 'Luke',
age: 27,
fave: 'Mew'
}
};
return new Promise(function(resolve, reject) {
if(data[name+age]) {
return resolve(data[name+age]);
}
return reject(new Error('No matching user found.'));
});
}
// Get the name
getName()
.then(function(name) {
console.log(name);
// Get the age
// Nested, because we need name to lookup
return getAge(name).then(function(age) {
console.log(name + ': ' + age);
// Get the user
return getUser(name, age);
});
})
// Disregard the name & age, as we have the user
.then(function(user) {
console.log(user);
})
.catch(function(e) {
console.log(e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment