Javascript Binding SQL results to a function

别来无恙 提交于 2019-12-11 01:40:41

问题


All,

I am working with WebOS enyo, but having a really senior moment....

Basically the fact its enyo has no relation to my question however...

I have a method:

clickPopulate: function(){

     // Do some SQL

};

I am using a database class to handle my SQL lite Db connection, the interface for the method i am using is:

 * Execute an arbitrary SQL command on the database.
 *
 * If you need to execute multiple commands in a transaction, use queries()
 *
 * Parameters:
 * - sql (string or query object, required)
 * - options (object):
 *    * values (array): replacements for '?' placeholders in SQL
 *      (only use if not passing a DatabaseQuery object)
 *    * onSuccess (function): method to call on successful query
 *        + receives single argument: results as an array of objects
 *    * onError (function): method to call on error; defaults to logging
 */


query: function(sql, options)

So anyway i send it some SQL and some options, one of which is the onSuccess callback.

this.$.db.query("SELECT fullName, count(*) FROM user WHERE username=? and password=? GROUP BY username",
        {values: [inUser,inPass], onSuccess: enyo.bind(this, this.callBackFunction)});

What i really want to be able to do is have the SQL result array return to my click handler function - clickPopulate, but as its the calling method, i cant get it to work?

Any ideas?


回答1:


You can't have an asynchronous callback return to the original caller.

The closest you can do is something like this (since I don't know the Enyo apis I'll just use some pseudo'ish stuff)

function clickPopulate() {
    db.query('Some SQL here', function(results) {
        //This is the code that will be run once the query is complete.
    });
}

So basically you can include a closure as the callback inside your function. This way it kind of looks like it's part of the original caller but it really isn't.


If you really wanted to, you could probably have it call the original function back, and define some parameter which is used to determine whether it's the results from the query, but that would just make it kinda ugly and confusing.



来源:https://stackoverflow.com/questions/6636456/javascript-binding-sql-results-to-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!