Skip to content

Instantly share code, notes, and snippets.

@JCloudYu
Last active September 15, 2018 05:29
Show Gist options
  • Save JCloudYu/45a82fb6cf88ffbe66ad9c4241f9f336 to your computer and use it in GitHub Desktop.
Save JCloudYu/45a82fb6cf88ffbe66ad9c4241f9f336 to your computer and use it in GitHub Desktop.
In case if I need a loop that requires heavy garbage collection...
(()=>{
"use strict";
module.exports = async_loop;
/**
* Provide asynchronous version of for / while loop controlling logic.
* This function mimic following logic using setTimeout mechanism.
*
* for ( init, condition, step ) { job }
*
* Sync that the asynchronous loop is composed by functions that don't share common scopes.
* There will be a shared object that allows developers to store variables that will be shared across the functions.
*
* @param {function({Function}, {Object})} job The main body of the loop
* @param {function({Object})|null} [condition=function(){}] Conditional-expression of for loop
* @param {function({Object})|null} [stepping=function(){}] Stepping-expression of for loop
* @param {function({Object})|null} [init=function(){}] Init-expression of for loop
* @returns {Promise} The promise will be resolved once the loop is finished
**/
function async_loop(job, condition=DO_NOTHING, stepping=DO_NOTHING, init=DO_NOTHING){
let stop = null;
let promise = new Promise((rs)=>{stop=rs;});
let shared_info = {};
let should_break = false;
let do_break=()=>{should_break=true};
let looper = async()=>{
if ( condition(shared_info) === false ) { return stop(); }
await job(do_break, shared_info);
if ( should_break ) { return stop(); }
stepping(shared_info);
setTimeout(looper, 0);
};
init(shared_info);
setTimeout(looper, 0);
return promise;
}
function DO_NOTHING(){}
/*
console.log( "FIRST LINE" );
let stop = 1;
await async_loop((brk)=>{
return new Promise((resolve)=>{
setTimeout(()=>{
console.log(stop++);
resolve();
}, 1000);
});
}, ()=>{return stop <= 30;});
console.log( "SECOND LINE" );
*/
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment