Same function call multiple times

48 views
Skip to first unread message

Abdullah Al Naiem

unread,
Jan 23, 2022, 10:19:57 PM1/23/22
to Chromium Extensions
in my js file
updateData(param1, param2){
    chrome.storage.local.get('mykey', function(data) { // customize mykey data
data = data + param1 + param2;
chrome.storage.local.set({ mykey: data });
});
}

if(value == "start"){
    updateData("A", "B");
}
if(value == "mid"){
    updateData("M", "N");
}
if(value == "last"){
    updateData("X", "Y");
}
// suppose calling this function more 5 times at once
This is actually my approach to execute the code but the problem is if the function call for 5 times but data is saving for 4 times (rarely happen and saved 3 times)

How can I solve this problem?

hrg...@gmail.com

unread,
Jan 24, 2022, 12:22:47 AM1/24/22
to Chromium Extensions, naie...@gmail.com
Make the  updateData function asynchronous.
Something like this (untested):

async updateData(param1, param2){
    let data = await chrome.storage.local.get('mykey') ;
data = data + param1 + param2 ;
await chrome.storage.local.set({ mykey: data }) ;
}

Then, you must use the function like this:

(async ()=>{ //a self executing asynchronous function so that we can use the await operator in it

    if(value == "start")
        await updateData("A", "B");
       
    if(value == "mid")
        await updateData("M", "N");
       
    if(value == "last")
        await updateData("X", "Y");
})();

Message has been deleted

Abdullah Al Naiem

unread,
Jan 26, 2022, 5:43:53 PM1/26/22
to Chromium Extensions, hrg...@gmail.com, Abdullah Al Naiem
ERROR: SyntaxError: await is only valid in async functions and the top level bodies of modules
Reply all
Reply to author
Forward
0 new messages