尝试使用coffescript来比较来自2台服务器的get API的结果 我写了下面的代码
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++
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++
问题是在getResponse完成之前调用compareResults,因为它返回异步。不知何故,我试图解决这个问题但最终无法弄清楚任何简单的问题。有人能帮助我吗?我是javascript的新手