Save results from a function in a variable Ionic 3 + Firestore

0

How do I save the result obtained in r.get ('quant') into a variable and return its value, because the first console.log shows the data I got, but the second does not, and the return quant always shows undefined on the console.

getQuantProduto(id, item){
var quant;
this.afs.collection(this.pedidos).doc(id).collection(this.itens).
doc(item).ref.get().then(function(r){
    quant = r.get('quant');
    console.log(quant);
})
console.log('quant');
return quant;

}

    
asked by anonymous 17.10.2018 / 02:25

1 answer

0

Because the function is asynchronous, the second console.log and return are executed before the this.afs.collection(this.pedidos).doc(id).collection(this.itens). doc(item).ref.get() function. To return the value, you need to put return inside the function:

getQuantProduto(id, item){
  var quant;
  this.afs.collection(this.pedidos).doc(id).collection(this.itens).
  doc(item).ref.get().then(function(r){
    quant = r.get('quant');
    console.log(quant);
    return quant;
})
    
17.10.2018 / 16:10