Link to home
Create AccountLog in
Avatar of Walter Grimm
Walter Grimm

asked on

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;
             };  
            }
Avatar of Zakaria Acharki
Zakaria Acharki
Flag of Morocco image

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

Avatar of Walter Grimm
Walter Grimm

ASKER

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,
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
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.
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();
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.
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
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
ASKER CERTIFIED SOLUTION
Avatar of Zakaria Acharki
Zakaria Acharki
Flag of Morocco image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
OK, thanx looks promising, very similar to my approach, will be in office in 2 days to test
Ok take your time, I hope it will work for you, I have already tested the code as a sample.
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
Really very great, even actively expanded the answer to a further step,