Poll for resource available with RequireJS

别说谁变了你拦得住时间么 提交于 2019-11-28 08:28:08

问题


So I'm writing an app using RequireJS and Socket.io that checks to see if the socket.io resource is available and then, on connection, bootstraps the app. In case socket.io ever temporarily goes down I'd like to have requireJS poll for the resource a few times until it is available and then continue on initializing the application.

Unfortunately (or maybe fortunately?) it seems like there is some sort of caching mechanism in require that registers scripterrors for scripts that don't load so that if you do a setTimeout in the error callback that retrys the socketio require function, require will continue to throw errors even when the resource becomes available.

Is this an oversight or is there a reason for keeping this error cached? More importantly, is there a workaround to allow require retrys?

Here's an example of what I've been trying:

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

回答1:


I know this is an old question, but it was intriguing to me so I looked into it...

There is a require.undef method you need to call in order to tell RequireJS not to cache the prior failure status of the load. See also errbacks example.

Then you can simply call require again with a null callback. The original callback will still be called -- no need for the recursion. Something like 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) {
            // 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();
});


来源:https://stackoverflow.com/questions/17599082/poll-for-resource-available-with-requirejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!