javascript - How do I convert synchronous ajax to asynchronous? -
what trying accomplish
i trying check server time , compare against preset closing time prevent user clicking on expired sale items (and display item has expired) hitting snag on how accomplish when it's mixed in synchronous call
i know async:false bad thought , won't work in firefox(works in chrome , ie) wanted. having hard time figuring out how convert code asynchronous. if alter part of code asynchronous other parts of code depends on falls apart because timing off.
previous code - phone call if sale_closed()
@get_server_time: (url) -> $.ajax( url: url + '/servertime' type: 'get' async: false ) @sale_closed: () -> if not @is_valid_user homecoming true if config.override_bid_closed? homecoming false if @get_server_time(url) > sale_end homecoming true homecoming false what tried that's not working
coffeescript
@get_server_time: (url) -> $.ajax( url: url + '/servertime' type: 'get' ) @sale_closed: () -> @get_server_time(url).done (data) -> if not @is_valid_user homecoming true if config.override_bid_closed? homecoming false if info > sale_end homecoming true homecoming false same code in
javascript:
function get_server_time (url) { homecoming $.ajax({ url: url + '/servertime', type: 'get' }); }; function sale_closed() { get_server_time(url).done(function(data) { if (!this.is_valid_user()) { homecoming true; } if (config.override_sale_closed != null) { homecoming false; } if (data > sale_end) { homecoming true; } homecoming false; }); }; is correct?
is expectation alter sale_close code from
foo: () -> if sale_closed() /* */ to
do_something: () -> /* */ foo: () - > sale_closed(do_something) that's giant nightmare because have alter lot of code , create them asynchronous may break other functions phone call 'foo', 'foo2', etc. (which synchronous before).
is there guarantee variables do_something read in context , have same value when execute?
thanks help seek wrap head around this
is correct?
not really. cannot return asynchronous callbacks in synchronous code. instead, want utilize promises:
@get_server_time: (url) -> $.ajax( url: url + '/servertime' type: 'get' ) @sale_closed: () -> if not @is_valid_user homecoming $.when true if config.override_bid_closed? homecoming $.when false @get_server_time(url).then (data) -> info > sale_end is expectation alter code calls sale_close?
yes, need alter callback style. promises, changes won't big though, , flow stays linear.
is there guarantee variables do_something read in context , have same value when execute?
you should declare do_something locally within foo function (or utilize function expression), guarantee variables need in scope. if need right this context, utilize fat arrow functions.
javascript jquery ajax asynchronous coffeescript
No comments:
Post a Comment