Created
August 22, 2017 14:14
-
-
Save tomekc/41ef4f5e99b35b1bdde50621e09a319a to your computer and use it in GitHub Desktop.
Branching inside promise chain (JavaScript, Bluebirdjs)
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'); | |
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