Skip to content

Instantly share code, notes, and snippets.

@ruffle1986
Created January 16, 2018 08:03
Show Gist options
  • Save ruffle1986/89de1f276ce27a9788df33a5a1b4d7ec to your computer and use it in GitHub Desktop.
Save ruffle1986/89de1f276ce27a9788df33a5a1b4d7ec to your computer and use it in GitHub Desktop.
Recursive async function
/**
* Usage of async function you want to call recursively:
*
* 1. We're responsible for resolving our own promise in the recursive async func.
* 2. We would like to execute other commands after the invoncation of the recursive func (line #32).
*
* Since we're creating a brand new promise in the function body, if we want to execute other code after the initial
* recursive call, it's important to resolve the first promise when you want to exit the recursion. Otherwise, the code after
* the first call (line #32) won't be executed at all.
*/
async function sleep(ms) {
return new Promise((r) => {
setTimeout(r, ms);
});
}
async function fakeFetch() {
return new Promise(r => r({ fakeData: true }));
}
async function recursive(n, cb) {
return new Promise(async r => {
if (n < 3) {
console.log('recur call.', n);
await sleep(1000);
await recursive(n + 1, cb || r);
n = n + 1;
} else {
(cb && cb(666)) || r(666);
}
});
}
(async function () {
const result = await recursive(0);
console.log('done.', result);
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment