轮询RequireJS提供的资源

所以我正在编写一个使用RequireJS和Socket.io的应用程序来检查socket.io资源是否可用,然后在连接时引导应用程序。 如果socket.io曾经暂时下降,我想有几次需要轮询资源,直到它可用,然后继续初始化应用程序。

不幸的是(或者幸运的是)似乎有某种caching机制要求为不加载的脚本注册脚本程序,以便如果在错误callback中执行setTimeout以反映socketio require函数,则require将继续甚至在资源可用时抛出错误。

这是一个疏忽还是有理由让这个错误caching? 更重要的是,是否有一个解决方法,允许需要重新?

以下是我一直在尝试的一个例子:

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

我知道这是一个古老的问题,但对我来说这很有趣,所以我仔细研究了一下。

有一个require.undef方法需要调用,以便告诉RequireJS不要caching之前的加载失败状态。 另请参阅errbacks示例。

然后,您可以简单地使用空callback调用require。 原来的callback仍然会被调用 – 不需要recursion。 像这样的东西:

 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(); });