У меня возникла проблема с областью javascript/порядком выполнения. Я создаю пустой объект внутри функции. Затем я добавляю некоторые свойства в дочернюю функцию. Однако свойства не изменились в родительской функции.Область действия функции/порядок выполнения 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;
};
К тому времени функция ребенка заканчивается, журнал консоли уже выполнено, поэтому «theResult» печатает пустые в этой строке. –
Вы забыли 'var'. Поэтому переменная 'theResult' является глобальной. – Pointy
Вам необходимо прочитать * асинхронные * запросы. – tymeJV