Last active
April 12, 2017 21:33
-
-
Save yurifrl/0a3baabdf4d1ce596c6e1dd375f9f6be to your computer and use it in GitHub Desktop.
Promise chaining
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
// TL;DR | |
// return arrays | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all | |
// http://stackoverflow.com/questions/28250680/how-do-i-access-previous-promise-results-in-a-then-chain | |
// http://stackoverflow.com/questions/22892681/what-patterns-are-there-for-passing-state-through-a-chain-of-promises-in-javascr | |
// http://bluebirdjs.com/docs/api/spread.html | |
// You design your api like aways, put when you want to pass a value, you pass Promise.all, and you do this in | |
// process of chaining it, your api, doesn't need to be awere of promises | |
it('Promise Chaining 1', async function() { | |
Promise.all([ | |
Promise.resolve('hello'), | |
]).spread(value => { | |
return Promise.all([Promise.resolve(value), Promise.resolve(value),]) | |
}).then(console.log) | |
.catch(console.log) | |
}) | |
it('Promise Chaining 2', async function() { | |
// The thing is, you return Promise.all | |
Promise.resolve('hello') | |
.then(value => Promise.all([Promise.resolve(value), Promise.resolve(value)])) | |
.spread((p1, p2) => { | |
// spread is a then that breaks all | |
// Do some function invoking, and arg passing | |
return [p1, p2, Promise.resolve(p2 + "asd")] | |
}) | |
.all() | |
.then(result => { | |
result.push("asdasdasd") | |
return result | |
}) | |
.then(console.log) | |
.catch(console.log) | |
}) | |
it('romise Chaining 3', function() { | |
const endpoints = [ | |
'http://www.mocky.io/v2/58ebc79227000098004892fe', | |
'http://mycustomdomain.lvh.me/v2/58ebc79227000098004892fe', | |
'http://www.mycustomdomain.lvh.me/v2/58ebc79227000098004892fe' | |
] | |
Promise.all(endpoints) | |
.then(endpoints => [ | |
endpoints, | |
Promise.all(map(pinger, endpoints)) | |
]) | |
.all() | |
.then(console.log) | |
.catch(console.log) | |
Promise.all(endpoints) | |
.then(endpoints => [endpoints, Promise.all(map(pinger, endpoints))]) | |
.all() | |
.then(console.log) | |
.catch(console.log) | |
Promise.all(endpoints) | |
.then(endpoints => Promise.all([endpoints, map(pinger, endpoints)])) | |
.then(console.log) | |
.catch(console.log) | |
Promise.all(endpoints) | |
.then(endpoints => [endpoints, map(pinger, endpoints)]) | |
.all() | |
.then(console.log) | |
.catch(console.log) | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment