Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

javascript - How to ensure the right parameters is passed to a function call declared in a loop?

I'm new to node, but I love it already. Only issue is, the asynchronous functionality is killing me.

I am using the google package to get my websites' rankings in google as so:

for (var j=0;j<keywords.length;j++) {
    var keyword = keywords[j];

    google(keyword, function(err, next, links) {

    console.log('Searching for keyword "' + keyword + '" in google.' + google.tld + ' ('+ google.lang +')');
      if (err) console.error(err);

      for (var i = 0; i < links.length; ++i) {

        var rank = i+1;

        console.log(keyword + ' #'+ rank + ' - ' + links[i].link + ' | ' + links[i].title);
        //link.href is an alias for link.link
        //console.log(links[i].description + "
");
      }
      console.log('
');
    });

}

My problem is that it the console log shows the same keyword for all websites, although I have defined three in my keywords array.

What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The immediate problem here is that the j and keyword variables go on changing before the callbacks are called.

A simple solution is to protect this variable in a closure :

for (var j=0; j<keywords.length; j++) {
    (function(j){
        var keyword = keywords[j];
        ...
    })(j);
}

When you're just working with a simple array, then you can also use a closure through forEach :

keywords.forEach(function(keyword, j){
     ...
});

To deal with this kind of asynchronous problems, you should now dive in promises which help structure your code in a clearer (and less indented) way. An introduction.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...