defage
V2EX  ›  Node.js

新手弱弱问一句, 我这个同步用法为啥就是不work?

  •  
  •   defage · Dec 9, 2013 · 4036 views
    This topic created in 4568 days ago, the information mentioned may be changed or developed.
    用async模块

    意图是有一串url api 在array里, [url1, url2, url3]
    用http.get执行之, 执行的结果收集到统一的var A = new Array() 里.
    var AAA = [];
    async.forEach(urls, function(url) {
    http.get(url, function(res) {

    var size = 0;
    var chunks = [];

    res.on('data', function(chunk){
    size += chunk.length;
    chunks.push(chunk);
    });

    res.on('end', function(){
    var data = Buffer.concat(chunks, size);
    AAA.push(data);
    });

    }).on('error', function(e) {
    cb(e, null);
    });
    });

    console.log(AAA);
    // ==> 最后这结果还是空的[]

    concat, series什么的都试过, 就是不行. 实在需要请求指教了. js新手, 各位请轻喷.
    3 replies    1970-01-01 08:00:00 +08:00
    leofml
        1
    leofml  
       Dec 9, 2013   ❤️ 1
    用map
    defage
        2
    defage  
    OP
       Dec 9, 2013
    @leofml 谢谢回复.
    我用了map过, 也不行.
    我都是直接在里面做push, 如果直接在push后log,能看到结果, 但在外面就被异步了
    defage
        3
    defage  
    OP
       Dec 9, 2013
    谢谢. 琢磨了下, 用map搞的差不多了. 谢谢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5297 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 06:51 · PVG 14:51 · LAX 23:51 · JFK 02:51
    ♥ Do have faith in what you're doing.