简体   繁体   中英

javascript promise in nested loop

Im trying unsuccessfully to loop through an array that has an array as one of the params, I need to loop through that nested array in order to map it according to specs, then I need to run a function after the parent loop completes. Can someone point out my mistake on getting this accomplished?

const schedule = {}
data.schedule.forEach(item => {
  let date = moment(item.date).format('YYYY-MM-DD')
  let eventList = []
  item.events.forEach(event => {
    let start = moment(event.start).format('h:mm A')
    let end = moment(event.end).format('h:mm A')
    let time = `${start} - ${end}`
    eventList.push({time: time, name: event.name})
  })
  return Promise.all(eventList).then(list => {
    console.log('list', list)
    schedule[`${date}`] = list
  })
})

// this is my issue:

Promise.all(schedule).then(list => {
  console.log('schedule:', list)
})

// which bombs the method with:
// TypeError: (var)[Symbol.iterator] is not a function
// at Function.all (native)

I actually need to return an object that resembles this:

{'2017-12-06': [
  {time: '9am - 10am', name: 'Jackson Home'},
  {time: '11AM - 3PM', name: 'Jackson Home'},
  {time: '3PM - 8PM', name: 'Jackson Home'}
]}

Yep, Im an idiot and need to take a beverage break:

const schedule = {}

  data.schedule.forEach(item => {
    let date = moment(item.date).format('YYYY-MM-DD')
    let eventList = []
    schedule[`${date}`] = item.events.map(event => {
      let start = moment(event.start).format('h:mm A')
      let end = moment(event.end).format('h:mm A')
      let time = `${start} - ${end}`
      return {time: time, name: event.name}
    })
  })

  console.log('schedule:', schedule)

As @charlietfl said, your code is not asynchronous, so you don't need Promise.

This code does what you needed:

const schedule = {}
data.schedule.forEach(item => {
  let date = moment(item.date).format('YYYY-MM-DD')
  let eventList = []
  item.events.forEach(event => {
    let start = moment(event.start).format('h:mm A')
    let end = moment(event.end).format('h:mm A')
    let time = `${start} - ${end}`
    eventList.push({time: time, name: event.name})
  })

  schedule[`${date}`] = eventList
})

For this input:

{
    schedule: [
        {
            date: '2017-01-01',
            events: [
                {
                    name: 'test',
                    start: '2017-01-01 10:00:00',
                    end: '2017-01-01 11:00:00'
                }
            ]
        }
    ]
}

... you get this:

{
    "2017-01-01": [
        {
            "time": "10:00 AM - 11:00 AM",
            "name": "test"
        }
    ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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