JS的序列函数如何使用promises

时间:2017-03-11 05:06:16

标签: javascript jquery

我有3个功能,只是尝试在点击时逐个运行它。如何做得更好,并停止得到像

这样的错误
  

未被捕捉TypeError:无法读取then的属性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())
});

1 个答案:

答案 0 :(得分:2)

您需要从每个函数返回Promises(jQuery中的Deferreds),并将函数作为处理程序传递给每个.then,而不是调用该函数的结果(即省略最终{{1 }})。

()
相关问题