我知道这是一个古老的问题,但这让我很感兴趣,所以我调查了一下…
您需要调用一个require.undef方法,以告知RequireJS不要缓存加载的先前失败状态。另请参见errbacks示例。
然后,您可以再次使用null回调再次调用require。原始回调仍将被调用-无需递归。像这样:
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) { // this is what tells RequireJS not to cache the previous failure status require.undef(failedId); retryCount++; console.log('retry ' + retryCount + ' of ' + retryLimit) setTimeout(function(){ // No actual callback here. The original callback will get invoked. require([libname], null, retryOnError); }, retryInterval); } else { console.log('gave up', err) } } // initial require of the lib, using the supplied callback plus our custom // error callback defined above require([libname], cb, retryOnError);}requireWithRetry('socketio', function(io) { io.connect('http://localhost'); app._bootstrap();});


