Actually, execution is happening at different times. Looking at your code, that's what it means.
The variable has the value of doc
, however you are giving console.log
out of callback
executed by then
. Therefore, before execution of then, no value will still be assigned to salvaAqui
.
Generally, promissory functions are used to make requests to parallel (or asynchronous) resources. When you give that console.log
at the end, with nothing being returned, it's absolutely understandable: the variable has not yet had the callback value of then
executed.
You have to understand that in javascript, the order of the code does not mean the order in which the results will be obtained. In an ajax request for example, the fact of giving a console.log
after your call would not change any value of the variable in the same scope as it was declared, but only after completion of the request.
Example:
var dados; // undefined
$http.get(url).then(function (response) {
dados = response.data; // [Object Object]
});
console.log(dados); // undefined
The suggestion in this case is to make the necessary operation with the data you need within the then
call.
Something like this:
db.get('mydoc').then(function(doc) {
processarDoc(doc); // passa como argumento
}).catch(function(err) {
console.log(err);
});
function processarDoc(doc) {
console.log(doc); // [Object Object]
}