0

I have to take each data of the array inside an array but it doesn't work when I use something like tmp.name or tmp[0].name would result undefined and even tmp.length result 0

var tmp = [];
var db = firebase.firestore();
var docCollection = db.collection('doctors');
var assignedDoctors = docCollection.where('assign', '==', user.key).get();

assignedDoctors.then(function(doc){
  let i = 0;
  doc.forEach(function(md){
    tmp.push(md.data());
    tmp[i].key = md.id;
    i++;
  });
}).catch(function(e){
  console.log(e);
});
console.log(tmp)

the tmp result

[]
0: {assign: "userA", name: "NameA"}
1: {assign: "userA", name: "NameB"}
length: 2
__proto_: Array(0)

newbie
  • 81
  • 8
  • 2
    `assignedDoctors` is a promise. Promises are `async`, you output `tmp` before the promise is fulfilled. Move `console.log(tmp)` inside the promise. – darklightcode Feb 13 '19 at 07:45
  • @darklightcode but I need it outside – newbie Feb 13 '19 at 09:30
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – vsemozhebuty Feb 13 '19 at 11:22

2 Answers2

0
var tmp = [];
var db = firebase.firestore();
var docCollection = db.collection('doctors');
var assignedDoctors = docCollection.where('assign', '==', user.key).get();

assignedDoctors.then(function(doc){
  let i = 0;
  doc.forEach(function(md){
    tmp.push(md.data());
   // tmp[i].key = md.id;
   // i++;
  });
}).catch(function(e){
  console.log(e);
});
console.log(tmp)

comment these line and check it.

Zoe
  • 27,060
  • 21
  • 118
  • 148
  • let test = []; let array = []; test.push('hi', 'hello', 'kkk'); console.log(test[0]); for (let i = 0; i < test.length; i++) { array.push(test[i]); } console.log(array); I did in type script but not your code same as like that. – Majutharan Majutharan Feb 13 '19 at 10:25
0

Just declare map and assign all data of md.data() to map and then push map into array and remove variable i as no need of it. Like following:

doc.forEach(function(md){
    var map = {};
    map = md.data();
    map.key = md.id;
    tmp.push(map);
  });
Sudhir Ojha
  • 3,247
  • 3
  • 14
  • 24