Skip to content

Instantly share code, notes, and snippets.

@herrera-ignacio
Created March 30, 2020 17:58
Show Gist options
  • Save herrera-ignacio/4d63f6116c793381fe8fc9f67a894b95 to your computer and use it in GitHub Desktop.
Save herrera-ignacio/4d63f6116c793381fe8fc9f67a894b95 to your computer and use it in GitHub Desktop.
Playing with Promises in Javascript
// Promises javascript example
// Maximize asynchronous benefits!
const makePromise = (num) => () => new Promise((resolve, reject) => {
return setTimeout(() => {
console.log(num)
resolve();
}, 1000 * Math.floor(3 * Math.random()))
});
const promises = [makePromise(1), makePromise(2), makePromise(3), makePromise(4)]
// Run promises asynchronously as an example
// You'll see they end in different orders each time
// promises.map((p) => p())
// SEQUENTIAL RUN
promises.reduce((res, nextPromise) => res
.then(() => nextPromise())
, Promise.resolve());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment