JavaScript. Return variable with asynchronism

0

I'm creating a Chrome extension.

I have the following function that I want to return True or False depending on the message answered. OK true, otherwise false. The function that must return true / false is sendMsgToBackgroundChangeStatus ()

function sendMsgToBackgroundChangeStatus(){
chrome.runtime.sendMessage({'since':'popup', 'activo': !activo}, function(response){
        //alert("Popup: " + response.status);
        //console.log("Popup: " + response.status);
        return response.status;
    }
);
}
if (SendMsgToBackgroundChangeStatus()){
   //block code
} else {
   //block code
}

There are several problems. The first problem is the execution of the code asynchronously. The second I do not know how I can get the result of a function inside another function.

The idea is that according to the answer from endMsgToBackgroundChangeStatus () (True or False) the conditional block code is executed (if (SendMsgToBackgroundChangeStatus ()))

Any ideas?

Thanks in advance.

Greetings.

    
asked by Enrique 26.02.2018 в 00:55
source

2 answers

1

Your problem is resolved with the use of promises.

function sendMsgToBackgroundChangeStatus() {
        return new Promise((resolve, reject) => {
            chrome.runtime.sendMessage({ 'since': 'popup', 'activo': !activo }, function (response) {
                response.status === 'VALID' ? resolve() : reject();
            });
        });
    }

    SendMsgToBackgroundChangeStatus()
        .then(() => console.log('ok'))
        .catch(() => console.log('fail'));
    
answered by 26.02.2018 в 17:49
-1

You can check this league:

link

Or you can also use libraries like Async or FutureJS to avoid callbacks hell.

And if you like, check this:

link

    
answered by 27.02.2018 в 00:54