Coffeescript wait for multiple api calls to be over
<p>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.</p>

<p>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</p>

<pre><code>    topChannels = []
    calcMsgCount = (value) -&gt;
     channelhistoryURL = 'https://some-url'
     msg.http(channelhistoryURL)
     .header('Accept', 'application/json')
     .get() (err, res, body) -&gt;
        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 &lt; 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) -&gt;
       array.sort((a,b) -&gt; b[key] - a[key])
    sortByMsgCount(topChannels, 'messagecount')
</code></pre>