0

Trying to come with a coffescript to compare the results of a get API from 2 servers I wrote the below code

http = require 'http'
component='frontend'
cm_app_host1='localhost:5000'
cm_app_host2='localhost:5000'#Assume some other IP
result=""
console.log url1
getResponse = (url,callbackfunc) ->
  req = http.get url, (res) ->
    status = res.statusCode
    body=''
    if status == 200
       res.on 'data', (chunk) ->
         body += chunk.toString()
       res.on 'end',() ->
         callbackfunc body
    else
      body+="ERROR"
  req.on 'error', ->
    msg = "not available"
    console.log msg


onFinish = (data) ->
  return data

compareResults = (str1,str2) ->
  console.log str1
  console.log str2
  return true #just for simplicity

j = 0
len = process.argv.length
while j < len
  campaignSendId=process.argv[2]
  console.log campaignSendId
  url1="http://"+cm_app_host1+"/cs/v1/someapi/"+campaignSendId+"?clientKey=00000000"
  url2="http://"+cm_app_host2+"/cs/v1/someapi/"+campaignSendId+"?clientKey=00000000"
  result1 = getResponse(url1, onFinish)
  result2 = getResponse(url2, onFinish)
  compareResults(result1,result2) #Gets called before we have recieved the results
  j++

Problem is compareResults gets called before getResponse completes since that returns asyncronously. Somehow I tried to solve this problem but eventually couldn't figure out anything simple. Can somebody help me? I am totally new to javascript

Akhtar
  • 93
  • 1
  • 9
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all – Jared Smith Sep 28 '16 at 15:04
  • Possible duplicate of [Node.js: Best way to perform multiple async operations, then do something else?](http://stackoverflow.com/questions/26268651/node-js-best-way-to-perform-multiple-async-operations-then-do-something-else) – Jared Smith Sep 28 '16 at 16:17

0 Answers0