Coffeescript & Promises

Using Coffeescript as a UI to JavaScript is one of the perks of programming ;)

Using the Promises Pattern when programming does line up your code and leave you with a perfect overview of your code!

That is - it was and did! Last week I tried marrying Coffeescript and jQuery Promises at the same time!

What do we want?

It really is rather unfair to mix up Promises into this post!

What we want is this kind of JavaScript - using the Promises Pattern to make sure that the Ajax calls back

return jqxhr = $.ajax({
  url: url,
  type: 'POST',
  dataType: 'script',
  data: data
}).done(function() {
  update_entrances = false;
  $('#status').html('Ok!');
  $('.alert').show();
  $('button.save_it').hide();
  if ($elem.hasClass('print_it')) {
    return window.print();
  }
}).fail(function() {
  return $('#status').html(jqxhr.responseText);
});

How do we get there?

I was very frustrated and tried a lot of things to get this to work - eventually giving in and asking this question on StackOverflow!

Luckily a guy called Ryan K came through, nursing me on my way and had me try a different approach with my Coffeescript syntax!

Lesson learned

When you set your eyes on adding Promises to an Ajax call, you'll have to be very careful with your Coffeescript syntax (as always but especially here):

post_changes = (url,data) ->
  jqxhr = $.ajax(
    url: url
    type: 'POST'
    dataType: 'script'
    data: data
  ).done( () ->
    $('button.update').hide()
    $('#status').html(jqxhr.responseText)
  ).fail () ->
    $('#status').html(jqxhr.responseText)