0

I have a function return an array data as below.

function get_info_tb(){
    var transaction = db.transaction(["mydb"]);
    var objectStore = transaction.objectStore("mydb");
    var request = objectStore.get("01");
    request.onerror = function(event) {
        alert("Unable to retrieve daa from database!");
    };
    request.onsuccess = function(event) {
        var data = request.result;
    };
    return data;
}

How to return varible data of request.onsuccess for get_info_tb?

I have a bit of a problem with the asynchronous of javascript. Please help me and thanks for everyone.!

1 Answers1

0

You can wrap it into the Promise and return that. Promise takes two functions - resolve and reject. You need at the success call resolve and reject at the error with appropriate parameters. And later chaining with then you can get these results. then accepts 2 parameters, one for the success and one for the failure. And your passed data from resolve and reject will be passed to the then functions appropriate callbacks.

function get_info_tb() {
   return new Promise((resolve, reject) => {

       var transaction = db.transaction(["mydb"]);
       var objectStore = transaction.objectStore("mydb");
       var request = objectStore.get("01");

       request.onerror = function(event) {
          reject();
       };

       request.onsuccess = function(event) {
          resolve(request.result);
       };

   });
}

and use

get_info_tb().then(data => { /* This is the success */ }, 
                   err => { /* This is the error*/ },)
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112