обратный вызов node.js, получающий неожиданное значение для переменной

Посмотрите мой вопрос:

, Кто такой лучший клиент подрывной деятельности для Linux?

я также соглашаюсь, клиенты GUI в Linux сосут.

я использую подзатмение в Eclipse и RapidSVN в гноме.

7
задан Jonas 27 April 2010 в 23:58
поделиться

1 ответ

This is perfectly normal behaviour. Your callbacks are executed at some later point (asynchronously) but still reference the scope your for loop was running in. All callback references to file will therefore have the last value it was set to.

What you want to do is create a new function scope, assign the current value of file to a local variable and create the callback inside that scope.

    for (var i=0;i<files.length;i++){
        var file = dir+'/'+files[i];
        (function() {
            var file_on_callback = file;
            sys.puts('file assigned: '+ file_on_callback);
            posix.stat(file_on_callback).addCallback(function(stats){
                sys.puts('stats returned: '+ file_on_callback);
                if (stats.isDirectory())
                    posix.readdir(file_on_callback).addCallback(function(files){
                        parse_file_list(file_on_callback, files);
                    });
                else if (stats.isFile())
                    process.watchFile(file_on_callback, restart_server);
            });
        })(); // This creates and executes a new function with its own scope.
    }
16
ответ дан 6 December 2019 в 12:51
поделиться
Другие вопросы по тегам:

Похожие вопросы: