Skip to content

Instantly share code, notes, and snippets.

@rajivnarayana
Created September 9, 2020 19:04
Show Gist options
  • Save rajivnarayana/41270faaebedee6a152509cbf7f22c09 to your computer and use it in GitHub Desktop.
Save rajivnarayana/41270faaebedee6a152509cbf7f22c09 to your computer and use it in GitHub Desktop.
Use array functions with async callbacks
/**
* A simple promise generator that waits for n seconds and returns a promise that resolves to n.
*/
function wait(n) {
return new Promise(resolve => setTimeout(resolve.bind(null, n), n * 1000));
}
/**
* A simple function that invokes promise and displays the result.
*/
async function simplePromise() {
console.log("Before wait(3)");
console.log(await wait(3));
console.log("After wait(3)");
}
/**
* A sample function that uses Promise.all to collect values in a array map function with async call back.
*/
async function async_map() {
const arr = [1,2,3];
console.log("Before map");
console.log(await Promise.all(arr.map(async x => {
return await wait(x);
})));
console.log("After map");
}
/**
* A sample function that adds a new Array function to collect values in a array reduce style function.
*/
async function async_reduce() {
const arr = [1,2,3];
console.log("Before reduce");
console.log(await arr.areduce(async (prev, x) => {
return prev + await wait(x);
}, 0));
console.log("After reduce");
}
// simplePromise();
// async_map();
Array.prototype.areduce = async function(cb, initial) {
let result = initial;
for(let i=0; i< this.length; i++) {
result = await cb(result, this[i]);
}
return result;
}
async_reduce();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment