Skip to content

Instantly share code, notes, and snippets.

@craig552uk
Last active February 16, 2016 10:16
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 craig552uk/85d3f7e155269c790d00 to your computer and use it in GitHub Desktop.
Save craig552uk/85d3f7e155269c790d00 to your computer and use it in GitHub Desktop.
Options for passing multiple data down a promise chain
// Promises can only resolve (return) a single value
// Sometimes, you want to collect multiple values as you progress through a promise chain
// e.g. Customer, Product, Basket, Payment Details
//
// I can only think of three options for handling this type of scenario (below)
// NB: Assume that FOO, BAR & BAZ are the result of some complex action (DB query etc.)
//
// What are the Pro's & Cons?
// Are there others?
// Option 1: Outside variables
var foo, bar, baz;
Promise.resolve("FOO").then(f => {
foo = f;
return "BAR";
}).then(b => {
bar = b;
return "BAZ";
}).then(z => {
baz = z;
console.log(foo, bar, baz);
});
// Option 2: Pass an array of accumulated values down the chain
Promise.resolve([]).then(data => {
data.push('FOO');
return data;
}).then(data => {
data.push("BAR");
return data;
}).then(data => {
data.push("BAZ");
return data;
}).then(data => {
console.log(data[0], data[1], data[2]);
});
// Option 2: Pass an object of accumulated values down the chain
Promise.resolve({}).then(data => {
data.foo = "FOO";
return data;
}).then(data =>{
data.baz = "BAZ";
return data;
}).then(data =>{
data.bar = "BAR";
return data;
}).then(data => {
console.log(data.foo, data.bar, data.baz)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment