简体   繁体   中英

Can I stop a function with the execution of a nested function?

I am trying to write a chrome extension and have the following code:

chrome.runtime.onMessage.addListener((req, sender, sendRes) => {
        function cancel_error() {
            sendRes({error:true});
            return;
        };

        if (!req || !req.type)
            cancel_error();
        cancel_error();
        console.log("continued");
        sendRes({testRespone: true});
    });

In this snippet the listener still logs continued and sends the test response. is there a way to stop the function like calling return with the execution of a nested function?

Just add return; after you call the function:

chrome.runtime.onMessage.addListener((req, sender, sendRes) => {
  function cancel_error() {
    sendRes({error:true});
  };
  if (!req || !req.type) {
    cancel_error();
    return;
  }
  console.log("continued");
  sendRes({testRespone: true});
});

Adding return after you call the function will work

if (!req || !req.type) {
    cancel_error();
    return;
  }

or if you want to perform logic in your function, I would just return a value and then check what that value is, and respond accordingly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM