javascript - Asynchronous JS Pre-Ecma2015 -
how 1 make own asynchronous functions without access things promises or async/await? i'm having no trouble finding examples of writing such things using these, requires newer versions of javascript. i'd know how you'd write such things without these newer features.
when write function accepted callback, example
let wait5 = function (callback) { let expire = date.now()+5000; while(date.now() < expire){ } console.log("waited 5 seconds!") if(callback) callback(); } wait5(function (){ console.log("called after waiting 5 seconds") }); console.log("this should log before 5 seconds passes"); the above not print log messages in order want, instead blocks on wait5() until it's done waiting. point wait5 meant emulate lengthy process, such sending , receiving on serial or parsing large amount of data, 1 might have long running loop , no set expected time of completion beyond 'eventually'.
so how make asynchronous without promises?
your code not asynchronous. while loop blocking, therefore function not end , following console.log in higher call stack isnt executed. same behaviour async functions too. not promises turn async code automatically. may use real asynchronity:
function wait5(callback){ settimeout(function(){ console.log("waited 5 seconds!") if(callback) callback(); },5000); } that can applied looping. instead of:
for( var = 0; < 1000000; i++) sth(i); one can do:
(function next(i){ sth(i); if(i < 1000000 - 1) settimeout(next,0,i+1); })(0);
Comments
Post a Comment