Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Branching inside promise chain (JavaScript, Bluebirdjs)
var Promise = require('bluebird');
console.log('=== Branching promises demo ===');
function getNameById(id) {
return Promise.resolve("Ziutek");
}
/*
Add missing data to object.
*/
Promise
.resolve({ id: '123' }) // starting with object with just id
.then( (data) => {
// Condition
if (!data.name) { // No name present? Let's fetch it
// and return array of promises
return [Promise.resolve(data), getNameById(data.id)];
}
// this promise always returns array of promises: [data, name]
return [Promise.resolve(data), null];
})
.spread((data, name) => { // here we will merge promises
return {
person_id: data.id,
person_name: name
}
})
.then(console.log);
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.