We are no longer accepting contributions to Documentation. Please see our post on meta.

JavaScript

How to make iterator usable inside async callback function All Versions

1
2
3
E4X
5
5.1
6
7
8
When using async callback we need to consider scope. Especially if inside a loop. This simple article shows what not to do and a simple working example.

This draft deletes the entire topic.

Examples

  • 0
    var pipeline = {};
    // (...) adding things in pipeline
    
    var processOneFile = function(key) {    
      fs.stat(pipeline[key].path, function(err, stats) {
        if (err) {
          // clear that one
          delete pipeline[key];
          return;
        }
        // (...)
        pipeline[key].count++;
      });
    };
        
    // verify it is not growing
    for(var key in pipeline) {
      processOneFileInPipeline(key);
    }
    

    By creating a new function, we are scoping key inside a function so all callback have their own key instance.

  • 0
    var pipeline = {};
    // (...) adding things in pipeline
    
    for(var key in pipeline) {
      fs.stat(pipeline[key].path, function(err, stats) {
        if (err) {
          // clear that one
          delete pipeline[key];
          return;
        }
        // (...)
        pipeline[key].count++;
      });
    } 
    

    The problem is that there is only one instance of var key. All callbacks will share the same key instance. At the time the callback will fire, the key will most likely have been incremented and not pointing to the element we are receiving the stats for.

Please consider making a request to improve this example.

Syntax

Syntax

Parameters

Parameters

Remarks

Remarks

Still have a question about How to make iterator usable inside async callback function? Ask Question

Topic Outline


    We are no longer accepting contributions to Documentation. Drafts cannot be modified.