Skip to content

Instantly share code, notes, and snippets.

@jakcharlton
Created May 25, 2011 09:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jakcharlton/990648 to your computer and use it in GitHub Desktop.
Save jakcharlton/990648 to your computer and use it in GitHub Desktop.
How do I return 'data' as the result of save_it ?
# How do I return 'data' as the result of save_it ?
save_it = (edited_value, s) ->
$.post(url_to_save_to, {value: edited_value}, (data) -> data)
@TrevorBurnham
Copy link

data doesn't exist until $.post returns, which will be after save_it runs, so there's no way to return data from save_it. You need to instead do whatever you were going to do with data from within the $.post callback. So for instance, instead of

input.val(save_it input.val())

you'd write

save_it input.val()

and

save_it = (edited_value, s) ->
    $.post(url_to_save_to, {value: edited_value}, (data) -> input.val data)

I hope that helps. CoffeeScript doesn't offer any particular structures to handle asynchronicity; "it's just JavaScript," as they say.

@TrevorBurnham
Copy link

By the way, if instead of $.post you were calling something that synchronously runs its callback, then you could write

save_it = (edited_value, s) ->
  data = null
  runNow (d) -> data = d
  data

to return the value provided by runNow from save_it. (The data = null line is necessary to give data scope outside of the callback.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment