i am writing a coffeescript, where i am calling around 1000 http URL 's, parsing each and every data from each call and creating an array of result objects. Finally i need to access the array of objects and sort them.
Whats happening is, the code is not waiting for each and every call to be over and instead goes to end of the code where i am sorting the result array. Since the api calls are not over, the resulting array is null and hence getting an exception. I am pasting my code below. Please help me here
topChannels = []
calcMsgCount = (value) ->
channelhistoryURL = 'https://some-url'
msg.http(channelhistoryURL)
.header('Accept', 'application/json')
.get() (err, res, body) ->
if res.statusCode is 200
try
data = JSON.parse body
Channel =
id: data.id
name: data.name
messagecount: data.messages.length
topChannels.push(Channel)
value++
if (value < response.channels.length)
setTimeout calcMsgCount(value),1000
catch err
msg.send "JSON parsing error"
msg.send value
msg.send err
else
msg.send "error while retrieving channel history"
index=0;
calcMsgCount(index);
# Sorting topChannels array based on total number of messages
sortByMsgCount = (array, key) ->
array.sort((a,b) -> b[key] - a[key])
sortByMsgCount(topChannels, 'messagecount')