0

I don't understand why i can't save my callback response in the global state var that i defined above. I store it in the response, but when i called it outside it always return undefined.

const state = {}    
    const initInfos = async () => {
        try {
                chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
                const message = {
                    name: 'loadInfos',
                    params: tabs[0]
                };
                Message.send(message, (res) => {
                    state.result = res.data; // store data in state.result
                     console.log(state.result) // display response from message
                });
            });
        }
        catch (e) {
            console.error(`error ${e}`);
        }
    };

    const controller = async () => {
        await initInfos();
        console.log(state.result); //display undefined
    };

    ['hashchange', 'load'].forEach((e) => window.addEventListener(e, controller));
Dujard
  • 271
  • 2
  • 7
  • 23
  • I think the function initInfos() is asynchronous so it do not wait for the function complete and just goto the next function controller (). That why state.result is undefined cause initInfos() is not finished yet and state do not have any data – Le Ngoc Thuong Oct 10 '19 at 12:12
  • If i use the await keyword before initInfos(), it do wait before next instruction no ? Even if i remove async word to test here, it stay to undefined – Dujard Oct 10 '19 at 12:40
  • Why did you make the controller async function? – Prawin soni Oct 10 '19 at 14:26
  • This might help: https://stackoverflow.com/questions/33289726/combination-of-async-function-await-settimeout – Prawin soni Oct 10 '19 at 14:55

0 Answers0