Set and visit global object in asynchronous functions

Code like this:

fileArray = ['a.json','b.json','c.json']
dict = {}
fileArray.map (f) ->
  fs.readFile f, (err, data) ->
    json.parse data, (k, v) ->
      dict[k] = v

I want to write the dict object to a file. How can I wait for all asynchronous functions finish?

Or is there any way else to do this?

You can do it manually like this

fileArray = ['a.json','b.json','c.json']
dict = {}
counter = 0
fileArray.map (f) ->
    fs.readFile f, (err, data) ->
        counter +=1
        json.parse data, (k, v) ->
            dict[k] = v
        if counter >= fileArray.length
            fs.writeFile("mydict.txt", dict.toString())

or you use a async library (for example https://github.com/caolan/async)

fileArray = ['a.json','b.json','c.json']
dict = {}
counter = 0
read = (file)->
    fs.readFile f, (err, data) ->
        json.parse data, (k, v) ->
            dict[k] = v

fns = ((do (file) -> read(file)) for file in fileArray)
#use the async lib
async.parallel fns, -> fs.writeFile "mydict.txt", json.stringify(dict)

Please take care I havent tested this.