Save a function’s results to an Ionic variable 3 + Firestore

Asked

Viewed 111 times

0

How to save the result obtained in r.get('Quant') in a variable and return its value, because the first console.log shows the data I obtained, 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;

}

1 answer

0

As the function is asynchronous, the second console.log and the return are executed before the function this.afs.collection(this.pedidos).doc(id).collection(this.itens). doc(item).ref.get(). To return the value, you need to put the return within 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;
})
  • thanks for the feedback, but when I do the following code: this. a = this.provider.getQuantProduct(123, abc), can’t get any returns yet

  • The console.log(quant); shows some value?

  • Yes, it correctly shows the value I seek, but Return does not return this value, it only returns Undefined

  • If it showed the correct value in console.log(quant), the function must have responded with the correct value. See if you are not trying to display the value of this.a before performing the function (asynchronous).

  • Maybe that’s it, in case how can I fix this problem?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.