0

我对 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;


};
4

3 回答 3

1

我认为您在声明变量之前忘记了“var”

var theResult = {} 
于 2015-11-30T17:25:59.737 回答
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)
});
于 2015-11-30T17:31:04.030 回答
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)); });
于 2015-11-30T17:31:27.237 回答