Javascript函数范围/执行顺序问题

时间:2015-11-30 17:20:38

标签: javascript scope monaca order-of-execution

我遇到了javascript范围/执行顺序的问题。我在函数内创建一个空对象。然后我在子函数中添加一些属性。但是,在父函数中,属性没有改变。

$scope.finder = function (obj) {

    var id = obj.oid;

    var crit = MC.Criteria('_ownerUserOid == ?', [id]);

    theResult = {}; // Scope should be finder function.

    database.findOne(crit) // This is a Monaca method for finding from database

    .done(function(result) {
        // Returns and empty object as expected.
        console.log(JSON.stringify(theResult));

        theResult = result;

        // Returns the search result object as again expected.
        console.log(JSON.stringify(theResult));
    });



// Here's the issue - when I log and return theResult, I get an empty object again.
// I think it has to do something with the scope.
// Also, this logs to console before either of the console.logs in the done function.

    console.log(JSON.stringify(theResult));
    return theResult;


};

3 个答案:

答案 0 :(得分:1)

我认为在声明变量

之前忘记了“var”
var theResult = {} 

答案 1 :(得分:0)

看起来您正在对某些数据执行异步请求。每次执行异步JavaScript时,都需要记住,事情不是按顺序调用的。当进行异步调用时,JavaScript将继续执行堆栈中的代码。

在您的情况下,theResult将是一个空对象,因为在您致电database.findOne(crit)console.log(JSON.stringify(theResult));尚未完成执行

因此,您无法从$scope.finder返回,而是可以将回调传递到$scope.finder并在database.findOne(crit)执行完毕后执行该回调。

$scope.finder = function (obj, callback) {

    var id = obj.oid;

    var crit = MC.Criteria('_ownerUserOid == ?', [id]);

    theResult = {}; // Scope should be finder function.

    database.findOne(crit) // This is a Monaca method for finding from database

        .done(function(result) {
            // Returns and empty object as expected.
            console.log(JSON.stringify(theResult));

            theResult = result;

            callback(theResult);

            // Returns the search result object as again expected.
            console.log(JSON.stringify(theResult));
        });
};

然后这样称呼它。

$scope.finder({some: 'data'}, function(response) {
    // response now has the values of theResult
    console.log(response)
});

答案 2 :(得分:0)

将其更改为:

$scope.finder = function (obj) {   
    return database.findOne(MC.Criteria('_ownerUserOid == ?', [obj.oid]));        
};

// Client code:
finder({ oid: 'foo' })
  .then(function(result) { console.log(JSON.stringify(result)); });