如何确保将正确的参数传递给循环中声明的函数调用? [英] How to ensure the right parameters is passed to a function call declared in a loop?

查看:79
本文介绍了如何确保将正确的参数传递给循环中声明的函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是节点的新手,但我已经喜欢它了。唯一的问题是,异步功能正在扼杀我。

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 + "\n");
      }
      console.log('\n');
    });

}

我的问题是控制台日志显示相同的关键字对于所有网站,虽然我在关键字数组中定义了三个。

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

我缺少什么?

推荐答案

这里的直接问题是 j 关键字变量继续改变之前调用回调。

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);
}

当你刚刚使用一个简单的数组时,你也可以使用通过 forEach

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

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

要处理这种异步问题,你现在应该深入了解有助于构建代码的promises更清晰(更少缩进)的方式。 简介

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.

这篇关于如何确保将正确的参数传递给循环中声明的函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆