Last active
August 29, 2015 14:04
-
-
Save lukemartin/c7ce365d6805f238020a to your computer and use it in GitHub Desktop.
Bluebird Promise Example
This file contains 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
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) | |
) |
This file contains 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
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