簡體   English   中英

Foreach 承諾所有數組問題

[英]Foreach promise all array issue

我的數組在 promise all 中有問題? 我嘗試為 foreach 的最后一次迭代運行一個函數,但我不明白為什么我的count_answers變量沒有為前一個對象設置? 正如你在 log 中看到的, count_answers只為最后一次迭代設置?? 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);
    }
  });
});

我的日志:

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

如果你需要另一個 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