Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...