0

I have the following code snippet :

function getCheckListTaskWithId(id){

 var tempTask = db.readTransaction(function (tx) {

      tx.executeSql('SELECT * FROM checklisttasks where id=? ', [id], function (tx, results) {
      var len = results.rows.length;
      if(len>0){
        var task=results.rows.item(0);
        var temp= new CheckListTask(task.id,task.crud,task.name,task.status);
        alert(temp);

      }   
    });

  });

}

the function that I pass to the tx.execute method is a call back function. Now I wan to return temp var present in callback function, from getCheckListTaskWithId function.

How Do I do this?

2 Answers 2

1

I am assuming that the executions of db.readTransaction and tx.executeSql are asynchronous. So you cannot return the result from them, as you don't know when they'll finish. The solution is use an asynchronous callback yourself. Make the getCheckListTaskWithId take a callback function as an argument and call it when result it available.

function getCheckListTaskWithId(id, callback) {
    var tempTask = db.readTransaction(function (tx) {
        tx.executeSql('SELECT * FROM checklisttasks where id=? ', [id], function (tx, results) {
            var len = results.rows.length;
            if(len > 0) {
                var task=results.rows.item(0);
                var temp= new CheckListTask(task.id,task.crud,task.name,task.status);
                alert(temp);
                callback(temp);
            }   
        });
    });
}
Sign up to request clarification or add additional context in comments.

Comments

0

Rewrite tx.executeSql so it gets the return value of the callback and returns it.

This assumes that tx.executeSql doesn't perform any Ajax. Ajax is Asynchronous, so an HTTP request is made, execution continues as normal and another function is run when the request comes back. In this case it is far too late to return a value to the earlier function and anything that needs to be done with the data can only be done by the callback.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.