Skip to content

Instantly share code, notes, and snippets.

@dtipson
Last active June 28, 2017 19:23
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 dtipson/d682c62f326fd66233f5c3cf1d0f7633 to your computer and use it in GitHub Desktop.
Save dtipson/d682c62f326fd66233f5c3cf1d0f7633 to your computer and use it in GitHub Desktop.
// mapping over an array with an async function
// would return an Array of Promises which isn't
// super useful to work with on its own
async function fooPromise(x){
return Promise.resolve(x*3);
}
const arr = [6,7,8,9];// -> [Promise[18],Promise[21],Promise[24],Promise[27]]]
// But we can fix that by sequencing them with Promise.all
Promise.all(R.map(fooPromise, arr))//-> Promise[[18,21,24,27]]
// This is because Promise.all is really an Array method that assumes Promises
// as a target type, not really a Promise method
// Now, if we used an async type that had some more generic interfaces...
function fooTask(x){
return Task((e,s)=>setTimeout(x=>x*3,400,x))
}
R.traverse(Task.of, fooTask, arr)//-> Task[[18,21,24,27]]
// Note that, unlike with Promises, this would be a pure operation.
// So the results are only conceptual because Task is lazy
// and has to be explicitly executed. fooTask also isn't
// an async function even though what's going on here has
// essentially the same end goal/purpose.
// The advantage of a generic interface is that there's no reason that the
// types have to be Arrays or Tasks or what have you. Sequencing/Traversing
// is a more primitive concept than that.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment