如何同步与异步的Node.js回调变量 [英] How to sync variable with async callback in node.js

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

问题描述

我有疑问,在以下code片段。

I have doubt in following code snippet.

for(var i=0; i<5; i++){
    http.request(option, function(res){
        console.log(i)
    });
}

这将打印的'我'为5,五倍的价值。有没有什么办法,使价值的'我'与功能(RES)的同步,可以打印0,1,2,3,4

This prints value of 'i' as 5, five times. Is there any way to make value of 'i' in sync with function(res) which can print 0,1,2,3,4

推荐答案

您必须给变量正确的范围。尝试是这样的:

You have to give the variables the correct scope. Try something like this:

for(var i=0; i<5; i++){
    (function(key) {
        http.request(option, function(res){
            console.log(key)
        });
    })(i);
}

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

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