Variable loses value after leaving Promisse

1
Hello, I'm having the following problem, I have a variable that should store the data coming from a promisse, so that this data can be used in other functions, but for some reason the variable saves the promisse data only when this promisse is running, after leaving it the variable returns to be undefined. I'm finalizing angle 1 and Pouchdb.

In PounchDB it is possible to get a JSON document from a database inside the browser.

   //Varivel que armazenda dados
   var salvaAqui;

   db.get('mydoc').then(function (doc) {
     salvaAqui = doc;
     console.log(salvaAqui); // Retorna resultado esperado.
   }).catch(function (err) {
   console.log(err);
   });

   console.log(salvaAqui); // Retorna undefined

I just need to know how to keep the "data" that promisse gave the variable. Anyone who can help me, I appreciate it.

    
asked by anonymous 18.08.2016 / 13:40

2 answers

2

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]
}
    
18.08.2016 / 13:59
0

The promisse runs after the rest of the code, so the value returns undefined. my solution was

    //Varivel que armazenda dados
    var salvaAqui;

    db.get('mydoc').then(function (doc) {
    salvaAqui = doc;
    executaResto();
    }).catch(function (err) {
    console.log(err);
    });

    function executaResto(){
       console.log(salvaAqui); // Agora retorna os dados normal
    }
    
18.08.2016 / 14:00