2

我有一个相当简单的 getUser 方法,但我遇到了一些麻烦。我对 JS 中的作用域等不是很熟悉,所以这让我很头疼。基本上我想从数据库中获取一个对象并将其返回给调用方法:

function getUser(uid)
{
    var result = null;

    var userTable = tables.getTable('Users');

    userTable.where({
        userId: uid
    }).read({
        success: function (results) {
            if (results.length > 0) {
                result = results[0];
                console.log('userid'+result.id);
            }
        }
    });
    console.log('userid-'+result.id); // undefined!!
    return result;
}

此外,从内部返回成功不会从 getUser 返回,而只是从内部定义的函数返回。我也试过“result = function(results)”,但它存储定义的函数而不是返回值。

我该怎么做?

4

2 回答 2

0

Because the call to the database is asynchronous, your last two lines are executed (and hence result is undefined) before the call the database actually finishes. So you need to handle everything inside your success callback. Or, if your getUser() func is a helper, you could structure your code (without recursion) like this with a callback:

function insertOrWhateverCallingMethod()
{
    var uid = 'blah';

    getUser(uid,function(user) {
        // Do something with the user object
    });

}

function getUser(uid,callback)
{
    var result = null;

    var userTable = tables.getTable('Users');

    userTable.where({
        userId: uid
    }).read({
        success: function (results) {
            if (results.length > 0) {
                result = results[0];
                console.log('userid'+result.id);
                callback(result);
            }
        }
    });
    callback(null);
}

The code above assumes you're in a table script, where the tables object is available - if it's not you can pass it as a parameter to getUser().

于 2014-01-21T18:08:29.070 回答
0

我在其他地方找到了解决方案。在实践中(据我所知),不可能在带有异步函数的 JavaScript 中做到这一点。您需要做的是从成功处理程序内部创建一个递归。

于 2014-01-21T11:29:55.867 回答