0

How would one make a nodejs application wait for async calls to finish?

main.coffee:

hosts = require './suhosts'
dns = require 'dns'
async = require 'async'

data = {}
async.each hosts, (host, cb_e) ->
   dns.lookup host,  (err, address, family)-> data[host] = address
 , () ->
   console.log data

if one runs this like coffee main.coffee it will exit before doing the work.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Mike Graf
  • 5,077
  • 4
  • 45
  • 58
  • 1
    Duplicate: http://stackoverflow.com/questions/6442676/how-to-prevent-node-js-from-exiting-while-waiting-for-a-callback – meyer9 Feb 18 '16 at 19:42
  • Normally, it would wait. What happens when you only do one lookup? – Ry- Feb 18 '16 at 19:42

1 Answers1

2

You’re not calling the required async.each callback.

data = {}
async.each hosts, (host, cb_e) ->
   dns.lookup host, (err, address, family) ->
      data[host] = address
      cb_e(err)
 , () ->
   console.log data
Ry-
  • 218,210
  • 55
  • 464
  • 476