0

I am trying to learn promises using jQuery (current version 3.2.1.)

I want to run the get request only after the post request is successful, but my current code does not work. Submitting the data works fine but the get request does not run. I am not sure how I can chain this two actions?

$('#newPoiForm').submit(function (e) { // handle the submit event
  e.preventDefault();
  let formData = $(this).serialize();
  console.log(formData);

  $.post({
      type: 'POST',
      url: '/api/pois/',
      data: formData
    }).done(function(){
      console.log('new asset submitted')
      return $.get({url: '/api/pois/last'})
    }).then(function (data) {
      // do stuff
  })
geogrow
  • 485
  • 2
  • 9
  • 26
  • There are multiple promise types. `success()`, `error()`, `then()`, `done()`, it depends on what you need. Id look up the api to discern what you are looking to accomplish. – Fallenreaper Jun 18 '18 at 19:54
  • 1
    `done` -> `then`. `done` is just a success callback, `.then` on the other hand will pipe the returned value and continue the chain. – Kevin B Jun 18 '18 at 19:55
  • Using then seem to work better. Will the second promise still run even if the first one fail? – geogrow Jun 18 '18 at 20:03
  • 1
    No, because the first callback to .then only gets called on success. – Kevin B Jun 18 '18 at 20:06

1 Answers1

0

Your issue here is using done() for the first callback - it's a legacy jQuery thing and doesn't chain promises. If you change it to then() it should work fine:

$.post({
  type: 'POST',
  url: '/api/pois/',
  data: formData
}).then(function(){           // don't use done()
  console.log('new asset submitted')
  return $.get({url: '/api/pois/last'})
}).then(function (data) {
  // do stuff
});

See this answer for more detail: jQuery deferreds and promises - .then() vs .done()

Duncan Thacker
  • 5,073
  • 1
  • 10
  • 20