簡體   English   中英

調用遞歸ajax時無法訪問成功功能

[英]Cant access success function when call recursive ajax

我正在構建一個具有推送通知功能並使用Jersey創建API的系統。
我讀了一篇有關彗星方法的文章 ,並以以下代碼結束:

Index.js

function checkExamNotification() {
    $.ajax({
        url: contextPath + '/api/notification/checkExamNotification',
        type: 'get',
        data: {
            accountId: accountId,
            sessionId: sessionId
        },
        success: function (res) {
            console.log("success");
            displayNumberOfNotification();
            checkExamNotification();
        },
        error: function (jqXHR, textStatus, errorThrown) {
            if (textStatus === "timeout") {
                checkExamNotification();
            }
        }
    });
}

$(document).ready(function () {
    $.ajaxSetup({
        timeout: 1000*60*3
    });
    checkExamNotification();
});

檢查考試通知API

@GET
@Path("/checkExamNotification")
public Response checkExamNotification(@QueryParam("accountId") int accountId, @QueryParam("sessionId") String sessionId) throws InterruptedException {
    if (memCachedClient.checkSession(sessionId, accountId)) {
        while (!examNotificationQueue.hasItems()) {
            Thread.sleep(5000);
        }

        ExamNotificationQueueItemModel examNotificationQueueItemModel = examNotificationQueue.dequeue();
        if (examNotificationQueueItemModel.getAccountId() == accountId) {
            LOGGER.info("[START] Check exam notification API");
            LOGGER.info("Account ID: " + accountId);
            LOGGER.info("Get notification with exam ID: " + examNotificationQueueItemModel.getExamId());

            ExamEntity exam = examDAO.findById(examNotificationQueueItemModel.getExamId());
            NotificationEntity notification = notificationDAO.findByExamId(exam.getExamid());
            notification.setSend(1);
            notificationDAO.getEntityManager().getTransaction().begin();
            notificationDAO.update(notification);
            notificationDAO.getEntityManager().getTransaction().commit();

            LOGGER.info("[END]");
            String result = gson.toJson(examNotificationQueueItemModel);
            return Response.status(200).entity(result).build();
        } else {
            examNotificationQueue.enqueue(examNotificationQueueItemModel);
            Thread.sleep(5000);
            checkExamNotification(accountId, sessionId);
        }

    }
    return Response.status(200).entity(gson.toJson("timeout")).build();
}

通過我的調試,API確實完成了返回,但是成功事件SOMETIMES並未觸發。
是的,有時控制台日志成功,但有時卻不成功。
有人可以向我解釋這種情況嗎?
提前致謝。 任何幫助,將不勝感激。

在關注@peeskillet評論之后,確定。 這是我的最終代碼。

檢查考試通知API

@GET
@Produces(SseFeature.SERVER_SENT_EVENTS)
@Path("/checkExamNotification")
public EventOutput checkExamNotification(@QueryParam("accountId") final int accountId, @QueryParam("sessionId") final String sessionId) {
    final EventOutput eventOutput = new EventOutput();
    if (memCachedClient.checkSession(sessionId, accountId)) {
        new Thread(new Runnable() {
            public void run() {
                try {
                    if (examNotificationQueue.hasItems()) {
                        ExamNotificationQueueItemModel examNotificationQueueItemModel = examNotificationQueue.dequeue();
                        if (examNotificationQueueItemModel.getAccountId() == accountId) {
                            LOGGER.info("[START] Check exam notification API");
                            LOGGER.info("Account ID: " + accountId);
                            LOGGER.info("Get notification with exam ID: " + examNotificationQueueItemModel.getExamName());
                            String result = gson.toJson(examNotificationQueueItemModel);
                            final OutboundEvent.Builder eventBuilder
                                    = new OutboundEvent.Builder();
                            eventBuilder.data(result);
                            final OutboundEvent event = eventBuilder.build();
                            eventOutput.write(event);
                            LOGGER.info("[END]");
                        } else {
                            examNotificationQueue.enqueue(examNotificationQueueItemModel);
                        }
                    }

                } catch (IOException e) {
                    throw new RuntimeException(
                            "Error when writing the event.", e);
                } finally {
                    try {
                        eventOutput.close();
                    } catch (IOException ioClose) {
                        throw new RuntimeException(
                                "Error when closing the event output.", ioClose);
                    }
                }
            }
        }).start();
    }

    return eventOutput;
}

Index.js

function checkExamNotification() {
    var url = contextPath + '/api/notification/checkExamNotification?accountId=' + accountId + '&sessionId=' + sessionId;
    var source = new EventSource(url);
    source.onmessage = function (event) {
        displayNumberOfNotification();
    };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM