Poll for resource available with RequireJS

后端 未结 1 894
南笙
南笙 2020-12-19 15:38

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

相关标签:
1条回答
  • 2020-12-19 15:47

    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();
    });
    
    0 讨论(0)
提交回复
热议问题