manyouuwx
manyouuwx

Reputation: 47

Foreach promise all array issue

I have an issue with my array inside promise all ? i try to run a function for the last iteration of foreach but i dont get it why my count_answers variable is not set for the previous object ? as you can see in log , the count_answers is only set for the last iteration ?? the arr[index].count_answers = count_answers is outside the condition of last iteration so what im doing wrong here ?

cleandata.forEach((child, index, arr) => {
  var getAnswers = FirebaseRef.child(
    'counter/questions/' + child.key + '/count_answers'
  ).once('value');
  Promise.all([getAnswers]).then(answer => {
    var count_answers = answer[0].val();
    arr[index].count_answers = count_answers;
    console.log('arr', arr);
    if (!arr[index + 1]) {
      console.log('arr_last', arr);
    }
  });
});

my log :

arr Array [
  Object {
    "created_at": 1574585699407,
    "date_upd": 1574585722870,
    "key": "-LuRbkkQpLCyaEv9-mKK",
    "question": "7",
  },
  Object {
    "count_answers": 2,
    "created_at": 1574584389276,
    "date_upd": 1574584399534,
    "key": "-LuRXktbNins7wqWUpjv",
    "question": "5",
  },
]
array_last Array [
  Object {
    "created_at": 1574585699407,
    "date_upd": 1574585722870,
    "key": "-LuRbkkQpLCyaEv9-mKK",
    "question": "7",
  },
  Object {
    "count_answers": 2,
    "created_at": 1574584389276,
    "date_upd": 1574584399534,
    "key": "-LuRXktbNins7wqWUpjv",
    "question": "5",
  },
]
arr Array [
  Object {
    "count_answers": 2,
    "created_at": 1574585699407,
    "date_upd": 1574585722870,
    "key": "-LuRbkkQpLCyaEv9-mKK",
    "question": "7",
  },
  Object {
    "count_answers": 2,
    "created_at": 1574584389276,
    "date_upd": 1574584399534,
    "key": "-LuRXktbNins7wqWUpjv",
    "question": "5",
  },
]

Upvotes: 1

Views: 87

Answers (1)

HMR
HMR

Reputation: 39350

If you need another ref then you can nest Promise.all, I assume both are based on child:

Promise.all(
  cleandata.map((child, index) =>
    Promise.all([
      FirebaseRef.child(
        'counter/questions/' + child.key + '/count_answers'
      ).once('value'),
      FirebaseRef.child(
        'counter/questions/' + child.key + '/other_ref'
      ).once('value'),
    ]).then(([answer, other]) => ({
      ...child,
      count_answers: answer.val(),
      other_ref: other.val(),
    }))
  )
).then(dataWithAnswers =>
  console.log('answers in clean data:', dataWithAnswers)
);

Upvotes: 1

Related Questions