Do I have to call return true each time I use onMessage.addListener responseCallback?

不打扰是莪最后的温柔 提交于 2019-12-13 10:14:37

问题


I have the a onMessage.addListener function like this:

chrome.runtime.onMessage.addListener(function (r, s, sendResponse) {
    if (r.action == "read") {
        readManga(request, function () {
            sendResponse({});
        }, true);
    }
    if (r.action == "write") {
        readManga(request, function () {
            sendResponse({});
        }, true);
    }
    if (request.action == "update") {
        $.each(request.list, function (index, val) {
            resetManga(val, function () {}, false);
        });
        saveList();
        refreshUpdate();
        sendResponse({});
    }
    if (request.action == "release") {
        releaseImplentationFromId(request.id, function (mirrorName) {
            updateMirrors(function () {
                sendResponse({
                    mirror : mirrorName
                });
            });
            return true
        });
    }
}

(this is an excerpt, but it's working code and please ignore all the if's, I should have used case since long ago)

Each time I use the callback function sendResponse (again, I need to rename it, but lets ignore that) as defined in the documentation is never used unless I have return true after it's execution. Is this really necessary or I just found a dirty hack and I'm doing something wrong?


回答1:


This is the expected behavior and clearly stated in the documentation:

This function [sendResponse] becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called).

Your function updateMirrors is apparently asynchronous: the callback function does not get executed immediately but is sent into a queue. So, you're not returning true "after" its execution, you are actually hitting return true before sendResponse.

Therefore, it's necessary to tell Chrome "expect an answer later".



来源:https://stackoverflow.com/questions/24398813/do-i-have-to-call-return-true-each-time-i-use-onmessage-addlistener-responsecall

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!