Node.js的:如何将变量传递给异步回调? [英] Node.JS: How to pass variables to asynchronous callbacks?

查看:192
本文介绍了Node.js的:如何将变量传递给异步回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定,我的问题是基于一个缺乏node.js的非同步编程的理解但在这里不用。

I'm sure my problem is based on a lack of understanding of asynch programming in node.js but here goes.

例如:我有我想要抓取的链接列表。当每个非同步请求返回我想知道它是哪个URL。但是,$ P $的psumably因为竞争情况,每个请求将返回设置为在列表中的最后一个值的URL。

For example: I have a list of links I want to crawl. When each asynch request returns I want to know which URL it is for. But, presumably because of race conditions, each request returns with the URL set to the last value in the list.

var links = ['http://google.com', 'http://yahoo.com'];
for (link in links) {
    var url = links[link];
    require('request')(url, function() {
        console.log(url);
    });
}

期望的输出:

http://google.com
http://yahoo.com

实际输出:

http://yahoo.com
http://yahoo.com

所以我的问题可以是:

So my question is either:


  1. 我如何通过URL(按价值计算)的回调函数? OR

  2. 什么是让他们按顺序运行链的HTTP请求的正确方法? OR

  3. 别的东西我失踪?

PS:对于1,我不希望它检查回调的参数,但回调知道有关变量的自上而下的一般方式加以解决。

PS: For 1. I don't want a solution which examines the callback's parameters but a general way of a callback knowing about variables 'from above'.

推荐答案

网​​址变量的作用域为循环,如JavaScript只支持全球和功能范围界定。所以,你需要为你的请求创建一个功能范围来电捕捉网​​址由循环的每个迭代值使用即时功能:

Your url variable is not scoped to the for loop as JavaScript only supports global and function scoping. So you need to create a function scope for your request call to capture the url value in each iteration of the loop by using an immediate function:

var links = ['http://google.com', 'http://yahoo.com'];
for (link in links) {
    (function(url) {
        require('request')(url, function() {
            console.log(url);
        });
    })(links[link]);
}

BTW,嵌入要求中环的中间是不是好的做法。它应该可能被重新写为:

BTW, embedding a require in the middle of loop isn't good practice. It should probably be re-written as:

var request = require('request');
var links = ['http://google.com', 'http://yahoo.com'];
for (link in links) {
    (function(url) {
        request(url, function() {
            console.log(url);
        });
    })(links[link]);
}

这篇关于Node.js的:如何将变量传递给异步回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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