Node.js的异步问题? [英] node.js asychronous issue?

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

问题描述

基本上我想循环通过现有arrtickers得到每个符号

然后阅读每个符号链接里面的内容,并保存内容纳入本地目录。

在PHP中,它会打印出每一个股票,并在一步步每个符号。

但在节点上,序列是乱起来......

它会先打印出所有的url_optionable ...

然后打印有时执行console.log('路径:'+文件)(!该文件被保存),有时打印的console.log;

每次通过fs.writefile功能运行,未检测到符号价值,保存的文件显示为MSN-的.html

不知道如何解决这个问题?

 为(VAR V = 0; V< arrtickers.length; v ++)
{    变种arrticker = arrtickers [V] .split('@@');
    变种符号= $ .trim(arrticker [1]);    url_optionable =htt​​p://sample.com/ns/?symbol=\"+sym;    的console.log('url_optionable:'+ url_optionable);    请求({URI:url_optionable},功能(错误,响应体){
      如果(误差放大器&;&安培; response.status code == 200!){
        的console.log('错误接触'+ url_optionable)
      }      jsdom.env({
        HTML:身体,
        脚本:
          jqlib
        ]
      },功能(呃,窗口){        变量$ = window.jQuery;
        VAR数据= $(身体)HTML()。        HTML - var文件=MSN+符号+;
        的console.log('路径:'+文件);        fs.writeFile(文件,数据,功能(错误){
            如果(ERR){
            的console.log(ERR);
            }
            其他
            {
                的console.log(以下简称文件被保存!);
                }
        });
      });
    });}


解决方案

ZeissS是正确的。基本上,你不能用里面的for循环中的回调函数,一个异步调用声明的变量,因为他们都将被设置为循环中的最后一个值。因此,在您code, url_optionable 符号将对应于 arrtickers [arrtickers。长度 - 1]

要么使用(如ZeissS建议):

  arrtickers.forEach(功能(arrticker){
    //获取符号和URL,使请求等
});

或宣布符号一个函数,它接受并执行的请求,并调用在循环:

 函数getSymbol(符号){
    //请求的URL和读取DOM
}为(变量V = 0; V族arrtickers.length; v ++){
    变种arrticker = arrtickers [V] .split('@@');
    变种符号= $ .trim(arrticker [1]);    getSymbol(符号);
}

就个人而言,我会选择在的forEach 解决方案。

Basically I want to loop through existing arrtickers to get each symbol

Then read the content inside each symbol url and save the content into local dir.

In php, it will print out each ticker and each symbol in step by step.

But in node, the sequences are mess up...

it will print out all the url_optionable first...

then sometimes print console.log('path: ' + file), sometimes print console.log("The file was saved!");

Everytime run through fs.writefile function, sym value is not detected, the saved file is show as msn-.html

Any idea how to fix this issue?

for(var v=0;v<arrtickers.length;v++)
{

    var arrticker= arrtickers[v].split('@@');
    var sym= $.trim(arrticker[1]);

    url_optionable= "http://sample.com/ns/?symbol="+sym;

    console.log('url_optionable: ' + url_optionable);

    request({ uri:url_optionable }, function (error, response, body) {
      if (error && response.statusCode !== 200) {
        console.log('Error contacting ' + url_optionable)
      }

      jsdom.env({
        html: body,
        scripts: [
          jqlib
        ]
      }, function (err, window) {

        var $ = window.jQuery;
        var data= $('body').html();

        var file= "msn-"+sym+".html";
        console.log('path: ' + file);

        fs.writeFile(file, data, function(err) {
            if(err) {
            console.log(err);
            } 
            else 
            {
                console.log("The file was saved!");


                }
        });


      });
    });

}

解决方案

ZeissS is right. Basically, you can't use variables declared inside the for loop in a callback function to an asynchronous call, because they will all be set to the last value in the loop. So in your code, url_optionable and sym will correspond to arrtickers[arrtickers.length - 1].

Either use (as ZeissS suggests):

arrtickers.forEach(function(arrticker) {
    // Get symbol and url, make request etc
});

Or declare a function which takes sym and does the request, and call that in your loop:

function getSymbol(symbol) {
    // Request url and read DOM
}

for(var v=0;v<arrtickers.length;v++) {
    var arrticker = arrtickers[v].split('@@');
    var sym = $.trim(arrticker[1]);

    getSymbol(sym);
}

Personally, I would opt for the forEach solution.

这篇关于Node.js的异步问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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