Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

node.js - How do you properly use await/async calls with forEach loops while making API calls?

The code is below. It is not looping through all of the items in the array and I think it's because async calls and forEach loops aren't the best solution for this.

async function getSubtotal(itemArray) {
  var total = 0.0
  try {
    itemArray.forEach(async (itemObject) => {
      let id = itemObject['id']
      console.log('itemId', id)
      const itemDoc = await db.collection('Menu').doc(id).get()
      const data = itemDoc.data()
      total += data.price
      console.log('total after item is appended', total)

      const selectedOptionIds = itemObject['selectedOptions']
      selectedOptionIds.forEach((optionId) => {
        const optionObject = data.allOptions
        optionObject.forEach((option) => {
          console.log('selectedOptionId', optionId)
          if (option.id === optionId) {
            total += option.price
            console.log('total after option is appended', total)
          }
        })
      })
    })
    console.log('finalTotal', total)
    return total * 100 // convert to cents
  } catch (error) {
    console.error(error)
    return { error: error }
  }
}
question from:https://stackoverflow.com/questions/65944178/how-do-you-properly-use-await-async-calls-with-foreach-loops-while-making-api-ca

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...