Skip to content

Instantly share code, notes, and snippets.

@atesgoral
Last active March 6, 2016 00:19
Show Gist options
  • Save atesgoral/c46bd90d0ee922e18b88 to your computer and use it in GitHub Desktop.
Save atesgoral/c46bd90d0ee922e18b88 to your computer and use it in GitHub Desktop.
Syntactical sugar experiments against promise indentation hell
return getFoo()
.then(foo => {
return getBar(foo)
.then(bar => {
return getBaz(foo, bar)
.then(baz => {
return getQux(foo, bar, baz);
});
});
});
return getFoo()
.then(foo => {
return getBar(foo);
})
.then(bar => {
return getBaz(foo, bar); // Bad reference: foo
})
.then(baz => {
return getQux(foo, bar, baz); // Bad reference: foo, bar
});
return magic('foo', getFoo())
.then(res => {
return magic('bar', getBar(res.foo));
})
.then(res => {
return magic('baz', getBaz(res.foo, res.bar));
})
.then(res => {
return getQux(res.foo, res.bar, res.baz);
});
return getFoo()
.then(magic(foo => {
return getBar(foo);
}))
.then(magic((foo, bar) => {
return getBaz(foo, bar);
}))
.then(magic((foo, bar, baz) => {
return getQux(foo, bar, baz);
}));
return contextualize(context => {
return getFoo()
.then(context(foo => {
return getBar(foo);
}))
.then(context((foo, bar) => {
return getBaz(foo, bar);
}))
.then(context((foo, bar, baz) => {
return getQux(foo, bar, baz);
}));
});
return collect({ foo: (collect) => {
return getFoo();
})
.then((collect) => {
return collect({ bar: getBar(collect.foo) });
}))
.then((collect) => {
return collect({ baz: getBaz(collect.foo, collect.bar) });
}))
.then((collect) => {
return collect({ qux: getQux(collect.foo, collect.bar, collect.baz) });
}));
magic({
foo: () => {
return getFoo();
},
bar: (foo) => {
return getBar(foo);
},
baz: (foo, bar) => {
return getBaz(foo, bar);
},
qux: (foo, bar, baz) => {
return getQux(foo, bar, baz);
}
});
return Promise.all({ foo: getFoo() })
.then((res) => {
return Promise.all(Object.assign({ bar: getBar(foo) }, res));
})
.then((res) => {
return Promise.all(Object.assign({ baz: getBaz(res.foo, res.bar) }, res));
})
.then((res) => {
return getQux(res.foo, res.bar, res.baz);
});
let theFoo = null;
let theBar = null;
let theBaz = null;
return Promise.resolve()
.then(() => {
return getFoo();
})
.then(foo => {
theFoo = foo;
return getBar(theFoo);
})
.then(bar => {
theBar = bar;
return getBaz(theFoo, theBar);
})
.then(baz => {
return getQux(theFoo, theBar, baz);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment