Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

  for player in players
	get_name_for = (player) ->
		ask "what's your name?", (response) ->
			if is_valid_name response
				player.name = response
			else get_name_for player
	get_name_for player


This looks like it does the wrong thing. If "ask" gets to access the scheduler's task list as a queue, then entering an invalid name in the first response and only valid names thereafter will cause the first valid name to be given to the second player, the second valid name to the third player, and so on. If "ask" gets to access the scheduler's task list as a stack, then a sequence of only valid input names will cause the last player to have the first input name, the second-last player to have the second input name, and so on.

Edit: I was optimistically assuming that the consumer of the many "asks" that are created all at once would process them sequentially, dealing with one and invoking the callback before dealing with the next. If you do not assume this, my problem disappears and you get the simpler problem of spawning many prompts simultaneously.


Hmm, I wrote it so that the function closes over the player, so that shouldn't happen. The real issue is, as pointed out, that this will ask for all the names at once, rather than sequentially. Wether this is bad or not depends on how the `ask` function gets its input.


This will ask two players simultaneously. My example waits for each player to provide a valid name in turn.


ok, sure, but it's still fixable without having to use await. you'd have to forego the for loop and make that flow control part of the callback cycle.

was your point that it couldn't be done with callbacks? or couldn't be done easily? or not easily alongside traditional flow control like for loops?

I agree, await and async in C# are very nice, I just took your post as a challenge.

  get_player_name = (player, next) ->
    ask "what's your name?", (response) ->
        if is_valid_name response
             player.name = response
             next!
    else get_player_name player, next

  get_player_names = ([player,...players]) ->
    get_player_name player, ->
    	if players.length > 0
            get_player_names players

  get_player_names players


Exactly, this was my point.

It took me about as long as I typed this code to write it.

Of course it is doable with callbacks, but I know I'm not smart enough to do it in a comment field on HN.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: