Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...