Search code examples
javascriptcallbacknw.js

JavaScript: custom callBack function


I'm new comer for js program, please excuse me if some not clear but let me know the problem.

Please see my code first:

function catchDataFromDB(db, tableName, callBack) {

var sqlStr = 'SELECT * FROM ' + tableName;
var sqlData = [];
db.transaction(function(t) {
        // Query out the data
        t.executeSql(sqlStr, [], function(t, SQLResultSet) {
            var len = SQLResultSet.rows.length,
                row;
            for (var i = 0; i < len; i++) {
                row = SQLResultSet.rows.item(i);
                sqlData.push(row);
            }
            console.log(sqlData);
        });
    },
    function(SQLError) {
        console.warn(SQLError.message);
    });
 return sqlData;
}

This function is used for gets the data from WebSql, and I want it returns the sqlData for me(it's an array). The problem is it's not finished gets data from the WebSql when I call the function to get the return value, so I got nil. I think callBack function will be useful for this to get the correct data, but I don't know how to do it. Thanks for any kindly help.

Additional: I've found a method from this page, the code as below:

function doSomething(callback) {
// ...

// Call the callback
callback('stuff', 'goes', 'here');
}

function foo(a, b, c) {
// I'm the callback
alert(a + " " + b + " " + c);
}

doSomething(foo);

But how to gets the return from function foo when I call function doSomething?


Solution

  • callback is simple function that is invoked when some works is complete, in javascript you can pass it in variable, so in your async/worker function you have to invoke callback function (like callback(result)) once it finishes the job.

    so your code should be

    function catchDataFromDB(db, tableName, callBack) {
      var sqlStr = 'SELECT * FROM ' + tableName;
      db.transaction(function(t) {
          // Query out the data
          t.executeSql(sqlStr, [], function(t, SQLResultSet) {
            var len = SQLResultSet.rows.length,
              row;
            for (var i = 0; i < len; i++) {
              row = SQLResultSet.rows.item(i);
              sqlData.push(row);
            }
            callBack(null, sqlData);
          });
        },
        function(SQLError) {
          callBack(SQLError.message);
        });
    }

    by convention callback's first argument should be error (if you have any), the rest of arguments are results
    callback(null, result1, result2,...) // when you have no error just result
    callback(error) // when you have error and no result