Skip to content

Instantly share code, notes, and snippets.

@jonchurch
Last active December 29, 2019 09:43
Show Gist options
  • Save jonchurch/9f1a9ae74740e182a3eb01093ad0fcb3 to your computer and use it in GitHub Desktop.
Save jonchurch/9f1a9ae74740e182a3eb01093ad0fcb3 to your computer and use it in GitHub Desktop.
Experimenting with sequential iteration using async/await
const array = [1, 2, 3];
function sleep(nSeconds) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(nSeconds), nSeconds * 1000);
});
}
async function run() {
for (const interval of array) {
await sleep(interval);
}
}
run();
const array = [1, 2, 3];
function sleep(nSeconds) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(nSeconds), nSeconds * 1000);
});
}
function endLog(n) {
console.log("Sequence complete, last item was", n);
}
async function doAsyncWork(accumulator, item) {
const result = await item;
accumulator.push(result);
return accumulator;
}
function accumulateAsync(accumulator, fn) {
return async (...rest) => {
// I want to give it an accumulator and a fn, and get back a fn that calls the fn and returns the accumulator
const result = await fn(...rest);
accumulator.push(result);
return accumulator;
};
}
// const sequentialPromise = array.reduce(async (lastPromise, item) => {
// const accumulator = await lastPromise;
// console.log(item);
// return doAsyncWork(accumulator, item);
// }, Promise.resolve([]));
// sequentialPromise.then(results => console.log(results));
// const pAcc = accumulateAsync([], sleep);
// const seq = array.reduce(async (lastPromise, item) => {
// await lastPromise;
// console.log(item);
// return pAcc(item);
// }, Promise.resolve());
// seq.then(result => console.log(result));
const asyncSeq = array.reduce(async (lastPromise, item) => {
await lastPromise;
console.log(item);
return sleep(item);
}, Promise.resolve());
asyncSeq.then(endLog);
const promiseSeq = array.reduce((lastPromise, item) => {
return lastPromise.then(() => {
console.log(item);
return sleep(item);
});
}, Promise.resolve());
promiseSeq.then(endLog);
const array = [1,2,3]
function sleep(nSeconds) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(nSeconds), nSeconds * 1000);
});
}
// Use reduce w/ an initial promise to sequentially run promises
const sequentialAsync = array.reduce(async (lastPromise, item) => {
await lastPromise;
return sleep(item);
}, Promise.resolve());
sequentialAsync
.then(n => console.log("Sequence complete, last item was", n));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment