I'm trying to write a script for hubot to get player statistics for a game, however I am having some trouble with list comprehension.
Here's my code
listings = []
listings =
(for player in players
request "http://pwa.wp3.pl/curvefever/?player=" + player , (err, res, body)->
$ = cheerio.load(body)
msg.send "Hello, world!1"
{name: $('b').slice(0).eq(0).text().toLowerCase(), rank: parseInt($('td').slice(37).eq(0).text(),10)})
msg.send "Hello, world!2"
for player of listings
msg.send "Hello, world!3"
msg.send player.name + " " + player.rank
when running this I get "Hello, world!2" followed by several "Hello, world!1" and no "Hello, world!3" as listings is (presumably) empty.
The script works when I do msg.send
instead of trying to capture the listings in an array, however I'd like to sort the listings based on rank too.
Several things are going in here.
First, you do not need to initialize
listings
as an array first.Second, I think you're looking for
for player in listings
.Third, and I think that's the most important point :
request
sends an ajax request. Ajax requests are, by definition, asynchronous.So what you actually push into your array is the result of "request" : probably nothing.
I'd recommend using a library such as async.js, a promise implementation, etc, or just a
i = players.length
that you decrement and check each time a request succeeds, to ensure your code awaits all results before it executes.