I recomend to use futures: http://en.wikipedia.org/wiki/Future_(programming)
Some implementations on node:
https://github.com/laverdet/node-fibers#futures
https://github.com/kriszyp/node-promise
https://github.com/nin-jin/node-jin#sod
etc

for example (run with --harmony flag):
===================================
var $= require( 'jin' ).loader()
    
var test= $.jin.sync2async( function test( ){
    var hash= {}
    
    void [ 'file1.csv', 'file2.csv' ]
    .map( function( path ){
        return $.fs.readFileSync( path ) // returns proxy-future immediately
    } )
    .forEach( function( content ){
        String( content )
        .split( /\r?\n/g )
        .forEach( function( row ){
            var fields= row.split( ';' )
            var key= fields[ 0 ]
            var val= fields[ 1 ]
            hash[ key ]= val
        } )
    } )
    
    console.log( hash )
} )

test()
===================================

пятница, 18 января 2013 г., 2:15:13 UTC+4 пользователь Jean-Michel Hiver 
написал:

> Hello,
>
> I getting started with node.js and its asynchronous nature is making me 
> wonder how to solve this problem.
>
> Consider the following piece of code:
>
> =======================
> var fs         = require('fs');
> var reader     = require ("buffered-reader");
> var DataReader = reader.DataReader;
>
> function test() {
>     var hash = [];
>     new DataReader ("./sunrise.csv", { encoding: "utf8" })
>         .on ("eof", function() {
>             console.log(hash);
>         })
>         .on ("line", function (line){
>               var reg    = new RegExp(";", "g");
>             var fields = line.split(reg);
>             var value  = fields[0];
>             var key    = fields[1];
>             hash[key]  = value;
>             console.log (hash[key]);
>          })
>         .read ();
>     console.log(hash);
> }
>
> test();
> =======================
>
> console.log(hash) displays [], most probably because it gets executed 
> before the ".on ("line", function (line){...}" piece...
>
> Could you let me know how to tell it to wait? What I want to do ultimately 
> is load a bunch of files into an associative array and ONLY THEN do 
> something with it.
>
> Any insights would be very much appreciated.
>
> Cheers
> JM
>

-- 
Job Board: http://jobs.nodejs.org/
Posting guidelines: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en

Reply via email to