Have function wait to return value with request.onsuccess in the function

I have a javascript codeblock for Indexeddb call, see below  

Link to sample: https://test.quality-auditors.com/IndexedDB/? 

I have found some sites on it, but i could not really identify how to solve it, maybe somebody can give me babysteps.

When I call this function, I recieve the reply immediatly, the function does not wait for the request.onsuccess to complete when finishing the function

So when i call this function, i cannot the recieve the final value, somehow I need to get the function to wait till the request.onsuccess has completed.  Can someone add just the lines of code so this would work.

I have added a callback , but this fires bevore the onsuccess routine calls the callback - it replies to the call in the line var request = objectStore.get(cursorkey);  

            alert('call at start: ' + getmyitem('a2d9592e-11c7-4d20-cccd-dd293988ce86'));

            function getmyitem(myuuid) {

                readitem(myuuid, function (dataset) {
                    alert('Data in getmyitem: ' + dataset);
                    return dataset
                });
            }

            function readitem(cursorkey, callback) {
            alert("Readdetails "+cursorkey);
                  var transaction = db.transaction(["note"]);  
                  var objectStore = transaction.objectStore("note");  
                  var request = objectStore.get(cursorkey);  
                request.onerror = function (event) {  
                callback('error');
                console.dir(event);
                  };  
                  request.onsuccess = function(event) {  
                var note = request.result;
                document.getElementById("noteDetail").innerHTML = "<h2>"+note.title+"</h2><p>"+note.body+"</p>";
                //$("#noteDetail").html("<h2>"+note.title+"</h2><p>"+note.body+"</p>");
                alert("Readdetails2 " + note.title);
                callback(note.title);
                //return note.title;
             };  
            }
LVL 1
Walter GrimmAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Zakaria AcharkiAnalyst DeveloperCommented:
Hi Walter,

The request you made is an asynchronous request so you should wait for the transaction to be performed then you'll get the result inside the "onsuccess" callback.

When you add a return statement and you call the function in your alert you wait for synchronous return that why it will not wait for the callback to be reached, and return immediately the non-desired value, instead you need to call the alert inside the in success to get the right final value, and do whatever you want there, like :

<a class="myuuid-anchor">[Readitem]</a>

function readitem(cursorkey) {
  var transaction = db.transaction(["note"]);  
  var objectStore = transaction.objectStore("note");  
  var request = objectStore.get(cursorkey);  

  request.onerror = function(event) {  
    console.dir(event);
  };  

  request.onsuccess = function(event) {  
    var note = request.result;
    document.getElementById("noteDetail").innerHTML = "<h2>"+note.title+"</h2><p>"+note.body+"</p>";

    alert("Readdetails2 "+ note.title );
 };
}

document.querySelector('.myuuid-anchor').addEventListener('click', function(e){
  e.preventDefault();

  readitem( document.getElementById('myuuid').value )
});

Open in new window


You could call another function inside your success callback if you want to perform any operations with the returned result like :

  request.onsuccess = function(event) {  
    var note = request.result;
    document.getElementById("noteDetail").innerHTML = "<h2>"+note.title+"</h2><p>"+note.body+"</p>";

    doSomethingWithResult( note );
 };

Open in new window

Walter GrimmAuthor Commented:
ok thanks,

I am aware of this, this is the reason I m usign the callback, which is said to elimintae this problem, make the function wait till the async actually call the callback.

What i am trying to achieve, is a wrapper for my indexeddb, that will return a json string with data, or a success for isert, update, delete,

So I am not wanting to call the alert in the onsuccess, but use the tech for asyncronous, to be able to await the procedure, so that i can pass the values to my caller.

there is also the promises and await tech,
Zakaria AcharkiAnalyst DeveloperCommented:
Ok I see, right now when using the provided code in my previous comment are you getting the proper value in your callback in the "request.result"?

You're welcome
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Walter GrimmAuthor Commented:
Hi Zakaria,

Yes, but this is standard JS, its this line in my code onsuccess here allready: alert("Readdetails2 "+ note.title );

What i need is to make a sync from an async function,

I am also getting it in the alert in the onsuccess in my sample, but i need it in the caller,

So i need to call the function, and have the async values returned.
Walter GrimmAuthor Commented:
FYI

 if you call the site https://test.quality-auditors.com/IndexedDB/? 

then paste this guid  a2d9592e-11c7-4d20-cccd-dd293988ce86

in the botton text box and than call the outer [Readme Test2]

I asume I need to wrap this around my code, but I am not great at syntax

async function f() {

  let promise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });

  let result = await promise; // wait till the promise resolves (*)

  alert(result); // "done!"
}

f();
Zakaria AcharkiAnalyst DeveloperCommented:
You need to use var note = event.target.result; instead, try console.log( event.target.result ); inside your success callback to see what the request return exactly.
Walter GrimmAuthor Commented:
Hi,

Do you have an idea, to make this async function wait till completed bevore getting back to caller,

The code above seems to be the solution, but I can't get the Syntax around my issue

Thanx
Walter GrimmAuthor Commented:
FYI this was the original article I referenced to solve the issue

https://stackoverflow.com/questions/22046587/how-come-function-doesnt-wait-for-another-function
Zakaria AcharkiAnalyst DeveloperCommented:
Here we go, Take a look at this sample :

function readitem(cursorkey, resolve) {
  console.log("Readdetails "+cursorkey);

  var transaction = db.transaction(["note"]);  
  var objectStore = transaction.objectStore("note");  
  var request = objectStore.get(cursorkey);  

  request.onerror = function (event) {  
    console.dir(event);
  };  

  request.onsuccess = function(event) {  
    var note = event.target.result;
    
    console.log( note );
    
    document.getElementById("noteDetail").innerHTML = "<h2>"+note.title+"</h2><p>"+note.body+"</p>";
    //$("#noteDetail").html("<h2>"+note.title+"</h2><p>"+note.body+"</p>");
    console.log("Readdetails2 ddd" + note.title);
    resolve(note.title);
  };  
}

function readItemAsync () {
  return new Promise(function (resolve) {
    readitem(document.getElementById('myuuid').value, resolve);
  })
}

async function sendRequest () {
  console.log("before");
  time = await readItemAsync();
  console.log("after");
}

Open in new window


You button will looks like :

<a onclick="sendRequest()">[Readitem]</a>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Walter GrimmAuthor Commented:
OK, thanx looks promising, very similar to my approach, will be in office in 2 days to test
Zakaria AcharkiAnalyst DeveloperCommented:
Ok take your time, I hope it will work for you, I have already tested the code as a sample.
Walter GrimmAuthor Commented:
Hi,

You seem to be good at js, interested in some paid projects, creating a js framework around signalr, Ajax and indexeddb

Technologies are all here, dedicated server etc
Walter GrimmAuthor Commented:
Really very great, even actively expanded the answer to a further step,
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.