javascript - Poll for resource available with RequireJS -


so i'm writing app using requirejs , socket.io checks see if socket.io resource available , then, on connection, bootstraps app. in case socket.io ever temporarily goes down i'd have requirejs poll resource few times until available , continue on initializing application.

unfortunately (or maybe fortunately?) seems there sort of caching mechanism in require registers scripterrors scripts don't load if settimeout in error callback retrys socketio require function, require continue throw errors when resource becomes available.

is oversight or there reason keeping error cached? more importantly, there workaround allow require retrys?

here's example of i've been trying:

function initialize() {   require(['socketio', function(io) {     io.connect('http://localhost');     app._bootstrap();   }, function(err) {     console.log(err);     settimeout(initialize, 10000);   }); } 

i know old question, intriguing me looked it...

there require.undef method need call in order tell requirejs not cache prior failure status of load. see errbacks example.

then can call require again null callback. original callback still called -- no need recursion. this:

function requirewithretry(libname, cb, retryinterval, retrylimit) {     // defaults     retryinterval = retryinterval || 10000;     retrylimit = retrylimit || 10;      var retrycount = 0;     var retryonerror = function(err) {         var failedid = err.requiremodules && err.requiremodules[0];         if (retrycount < retrylimit && failedid === libname) {             // tells requirejs not cache previous failure status             require.undef(failedid);              retrycount++;             console.log('retry ' + retrycount + ' of ' + retrylimit)              settimeout(function(){                 // no actual callback here. original callback invoked.                 require([libname], null, retryonerror);             }, retryinterval);          } else {             console.log('gave up', err)         }     }      // initial require of lib, using supplied callback plus our custom     // error callback defined above     require([libname], cb, retryonerror); }  requirewithretry('socketio', function(io) {     io.connect('http://localhost');     app._bootstrap(); }); 

Comments