javascriptindexeddb

I would like to make the below code to execute synchronous


Below is the code I want to make synchronous

subtractBtn.addEventListener("click",  (e) => {

    console.log("executing");
    readDatafromDB();
    console.log("executing after read");

});



function readDatafromDB() {

    const db_store = createTransaction("readwrite");
    const data = db_store.get(79);

    console.log("executing 2");
    
    data.onsuccess =  function(e) {       
        var data = e.target.result;
        console.log("data is: ", data);
    };

    data.onerror = function(e) {

    };
    console.log("executing 4");
}

Since reading data from indexedDB is async the following the being printed:

executing
executing 2
executing 4
executing after read
data is: 

However, I would want the code to execute in the below way synchronously

executing
executing 2
data is: 
executing 4
executing after read

I tried in all possible, and seems impossible


Solution

  • Here is a code with promise:

    subtractBtn.addEventListener("click", async (e) => {
        console.log("executing");
        await readDatafromDB();
        console.log("executing after read");
    });
    
    function readDatafromDB() {
        return new Promise((resolve, reject) => {
            const db_store = createTransaction("readwrite");
            const data = db_store.get(79);
    
            console.log("executing 2");
    
            data.onsuccess = function (e) {
                var data = e.target.result;
                console.log("data is: ", data);
                console.log("executing 4");
                resolve(); // Resolve the promise once the data is retrieved
            };
    
            data.onerror = function (e) {
                reject(e); // Reject the promise if an error occurs
            };
        });
    }
    

    I hope this helps