Alex
Alex

Reputation: 81

Sequence of JS functions how to make with promises

I have 3 functions, and just trying to run it one by one on click. How to do it better and stop to get an errors like

Uncaught TypeError: Cannot read property then of undefined?

 function msgRequest() {
    $.post('/admin/notify/messages', {"_token": "{{ csrf_token() }}"}, function (messages) {
    })
}

function readAll() {
        $.each(messages, function (index, message) {
            $.post('/admin/notify/read', {notify_id : message.id,"_token": "{{ csrf_token() }}"} ,function (data) {
            });
        });
}

 function getUnread() {
    $.post('/admin/notify/unread', {"_token": "{{ csrf_token() }}"} ,function (unread) {
        $('#unread').text(unread);
    });
}

$('#readall').click(function () {
   msgRequest().then(readAll()).then(getUnread())
});

Upvotes: 0

Views: 49

Answers (1)

gyre
gyre

Reputation: 16779

You need to return Promises (Deferreds in jQuery) from each of your functions, and pass a function to each .then as a handler rather than the result of calling that function (i.e., omit the final()).

function msgRequest() {
  return $.post('/admin/notify/messages', {
    "_token": "{{ csrf_token() }}"
  }).promise()
}

function readAll(messages) {
  return $.when.apply(null, $.map(messages, function(index, message) {
    return $.post('/admin/notify/read', {
      notify_id: message.id,
      "_token": "{{ csrf_token() }}"
    }).promise()
  }));
}

function getUnread() {
  return $.post('/admin/notify/unread', {
    "_token": "{{ csrf_token() }}"
  }, function(unread) {
    $('#unread').text(unread);
    return unread
  });
}

$('#readall').click(function() {
  msgRequest().then(readAll).then(getUnread)
});

Upvotes: 2

Related Questions