Last active
June 11, 2021 04:32
-
-
Save crazy4groovy/c18841f20cf9a1ae04a396f759ac3278 to your computer and use it in GitHub Desktop.
Example of how to "recursively" call an async function, using the event loop (setTimeout). (NodeJS)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function delay(ms) { | |
return new Promise(res => setTimeout(res, ms)); | |
} | |
function fnDefine(arr) { // some external params, whatever | |
return async function work(recurse, resolve, reject) { // <<< API defined | |
await delay(100); | |
const num = Math.random(); | |
const more = (num > .5); // arbitrary condition | |
if (!more) { | |
resolve(arr); // end recursion | |
return; | |
} | |
arr.push(num); | |
const ms = 100; | |
recurse(ms); // execute recursion | |
} | |
} | |
async function fnRecurse(work) { | |
async function main(resolve, reject) { | |
// recursion defined: execute main with (resolve, reject) | |
const recurse = (ms = 1) => setTimeout(main, ms, resolve, reject); | |
try { | |
await work(recurse, resolve, reject); // <<< API executed | |
} | |
catch (err) { reject(err); } | |
} | |
return new Promise(main); | |
} | |
// test: | |
// const result = await fnRecurse(fnDefine([])) | |
// fnRecurse(fnDefine([])).then(console.log) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment