我定义了以下Javascript函数:
function RecoverDataFromTable(table_name) {
query = "";
//some code that build a query string from table_name and
//other arguments given to the function
function Query(database) {
database.executeSql(query, [], RecoverResults, Error)
}
function RecoverResults(database, results) {
var my_result = results.rows(0).id;
// assume this works and store a value to my_result
}
function Error(error) {
//alert something
}
function Success() {
//alert something
}
database.transaction(Query, Error, Success)
}
现在,我怎样才能返回my_result值,以便我能做到这一点?
var my_var = RecoverDataFromTable(table_name, argument1, argument2.....)
提前致谢。 询问您是否需要更多解释。 :)
http://www.raymondcamden.com/index.cfm/2012/1/6/Working-with-dates-and-SQLite-in-PhoneGap
答案 0 :(得分:1)
你无法真正设置这样的变量,因为该函数是异步的。相反,您应该在 RecoverDataFromTable 的请求中包含回调功能。像这样定义:
function RecoverDataFromTable(callback, table_name) {
...
function RecoverResults(database, results) {
var my_result = results.rows(0).id;
// assume this works and store a value to my_result
// make the callback:
callback(result);
}
...
}
然后拨打电话:
function handleResult(my_result)
{
// handle the result here
}
RecoverDataFromTable(handleResult, table_name, argument1, argument2.....);
答案 1 :(得分:0)
如果您的函数RecoverResults是异步的,那么您可以使用to ::
function RecoverDataFromTable(callback, table_name) {
...
function RecoverResults(callback, database, results) {
var my_result = results.rows(0).id;
callback(my_result);
// assume this works and store a value to my_result
}
}
RecoverDataFromTable(function(result) {
var my_var = result;
}, table_name, argument1, argument2.....);
答案 2 :(得分:0)
不是吗?
function RecoverResults(database, results) {
return results.rows(0).id;
}
var my_result = RecoverResults();