Return value from nested function to parent without using callback

I wrote the following function to check if my HTML5 openDatabase table is HTML5 openDatabase or empty:

 var that = this; that.db = openDatabase('dbname', '1.0', "description", 1024 * 1024); that.tableFilled = function( tableName ) { that.db.transaction(function ( tx ) { tx.executeSql('SELECT * FROM ' + tableName, [], function success( c, results ) { return ( results.rows.length > 0 ? true : false ); }, function fail() { console.log('FAiL'); } ); }); }; 

I am trying to return true or false to tableFilled() .

Actually that.tableFilled('tableName') returns undefined .

In the end, I try to achieve:

 if ( that.tableFilled('tableName') ){ // ... } 

Is it possible to use return values true or false for the parent function tableFilled() without using a callback ?

+4
source share
1 answer

You are dealing with an asynchronous process, so you cannot directly return a value.

However, you can make a promise . Your function promises to give you this value when it is available. To get value from a promise, you must add a callback function.

You still need to use the callback function, but you no longer need to wipe your functions anymore, you can just serialize them.

It may be a way out of the scope of your current needs, but it is a very interesting concept. Just google if you want to know more.

Here is a quick example:

 function my_function() { var promise = new_promise(); do_asynchronous(function callback(result) { promise.resolve(result); // gets called after 1 second }); return promise; } var promise = my_function(); promise.done(function(result) { console.log(result); // prints "yay!" after 1 second }); function new_promise() { var handlers = []; return { "resolve": function (result) { for (var i = 0; i < handlers.length; i += 1) { handlers[i](result); } }, "done": function (a_callback) { handlers.push(a_callback); } }; } function do_asynchronous(callback) { setTimeout(function () { callback("yay!"); }, 1000); } 
+5
source

Source: https://habr.com/ru/post/1395840/


All Articles