Skip to content

Instantly share code, notes, and snippets.

@tomekc
Created August 22, 2017 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomekc/41ef4f5e99b35b1bdde50621e09a319a to your computer and use it in GitHub Desktop.
Save tomekc/41ef4f5e99b35b1bdde50621e09a319a to your computer and use it in GitHub Desktop.
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