简体   繁体   English

Foreach 承诺所有数组问题

[英]Foreach promise all array issue

I have an issue with my array inside promise all ?我的数组在 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 ?我尝试为 foreach 的最后一次迭代运行一个函数,但我不明白为什么我的count_answers变量没有为前一个对象设置? as you can see in log , the count_answers is only set for the last iteration ??正如你在 log 中看到的, count_answers只为最后一次迭代设置?? the arr[index].count_answers = count_answers is outside the condition of last iteration so what im doing wrong here ? arr[index].count_answers = count_answers超出了上次迭代的条件,所以我在这里做错了什么?

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",
  },
]

If you need another ref then you can nest Promise.all, I assume both are based on child:如果你需要另一个 ref,那么你可以嵌套 Promise.all,我假设两者都基于 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)
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM