Promise.resolve与数组

时间:2019-05-09 03:55:56

标签: javascript arrays promise

我有以下代码。其目的是从数据库中获取数据并将其格式化为JSON对象,以便它们与VueCal兼容。

我正在从数据库中请求数据,然后获取每个结果并创建一个JSON对象,将该对象推入数组,然后使用Promise.resolve([array name])希望返回带有诺言的数组。

我将其包装在Promise.all块中,然后将所有这些已解决的Promise添加到另一个数组中。最后的数组包含4个未定义的元素。为什么会这样?

try {
    const results = await Promise.all([
      Budget.find({
        userEmail: req.body.userEmail
      })
        .then(budgets => {
          let budgetsFormatted = []
          for (let i = 0; i < budgets.length; i++) {
            if (budgets[i].startDate) {
              var startBegin = moment(budgets[i].startDate, 'YYYY-MM-DD HH:mm')
              var endBegin = moment(budgets[i].startDate, 'YYYY-MM-DD HH:mm').add(1, 'hour')
              var startEnd = moment(budgets[i].startDate, 'YYYY-MM-DD HH:mm').add(budgets[i].duration, 'days')
              var endEnd = moment(budgets[i].startDate, 'YYYY-MM-DD HH:mm').add(1, 'hour')
            } else {
              continue
            }
            budgetsFormatted.push({
              title: budgets[i].title,
              start: startBegin,
              end: endBegin,
              content: octicons.credit_card + '<br>£' + budgets[i].amount
            })
            budgetsFormatted.push({
              title: budgets[i].title,
              start: startEnd,
              end: endEnd,
              content: octicons.credit_card + '<br>£' + budgets[i].amount
            })
          }
          console.log(budgetsFormatted)
          Promise.resolve(budgetsFormatted)
        })
        .catch(err => {
          Promise.reject(err)
        }),

      Notes.find({
        userEmail: req.body.userEmail
      })
        .then(notes => {
          let notesFormatted = []
          for (let i = 0; i < notes.length; i++) {
            if (notes[i].dateCreated) {
              var start = moment(notes[i].dateCreated, 'YYYY-MM-DD HH:mm')
              var end = moment(notes[i].dateCreated, 'YYYY-MM-DD HH:mm').add(1, 'hour')
            } else {
              continue
            }
            notesFormatted.push({
              title: notes[i].title,
              start: start,
              end: end,
              content: octicons.note + '<br>' + notes[i].body.substr(1, 10) + '...'
            })
          }
          console.log(notesFormatted)
          Promise.resolve(notesFormatted)
        })
        .catch(err => {
          Promise.reject(err)
        }),

      StudyPlan.find({
        userEmail: req.body.userEmail
      })
        .then(studyplan => {
          let studyPlansFormatted = []
          for (let i = 0; i < studyplan.length; i++) {
            for (let j = 0; j < studyplan[i]['daysAndTimes'].length; j++) {
              if (studyplan[i]['daysAndTimes'].timeFrom) {
                var start = moment(studyplan[i]['daysAndTimes'].timeFrom, 'YYYY-MM-DD HH:mm')
                var end = moment(studyplan[i]['daysAndTimes'].timeFrom, 'YYYY-MM-DD HH:mm').add(studyplan[i]['daysAndTimes'].duration, 'hours')
              } else {
                continue
              }
              studyPlansFormatted.push({
                title: studyplan[i].title,
                start: start,
                end: end,
                content: octicons.pencil
              })
            }
          }
          console.log(studyPlansFormatted)
          Promise.resolve(studyPlansFormatted)
        })
        .catch(err => {
          Promise.reject(err)
        }),

      TodoList.find({
        userEmail: req.body.userEmail
      })
        .then(todolists => {
          let todoListsFormatted = []
          for (let i = 0; i < todolists.length; i++) {
            if (todolists[i].dateDue) {
              var start = moment(todolists[i].dateDue, 'YYYY-MM-DD HH:mm')
              var end = moment(todolists[i].dateDue, 'YYYY-MM-DD HH:mm').add(1, 'hours')
            } else {
              continue
            }

            todoListsFormatted.push({
              title: todolists[i].title,
              start: start,
              end: end,
              content: octicons.tasklist
            })
          }
          console.log(todoListsFormatted)
          Promise.resolve(todoListsFormatted)
        })
        .catch(err => {
          Promise.reject(err)
        })
    ])

    const events = [].concat.apply([], results)

编辑:

将代码保留在此处,以防有人想看。但这是代码的基本结构:

const results = await Promise.all([
  //Find data in Database
  |
   ->  //Format result to be a JSON object like the following:
        {
          title: 'Event Title',
          start: //Start date of event,
          end: //End date of event,
          content: '<content> of event object in </calendar>'
        }
        //Add this object into array
        Promise.resolve(the above referenced array)

  //Repeat the above for each collection in the database

])

const events = [].concat.apply([], results)

1 个答案:

答案 0 :(得分:2)

您忘记了在每个Promise处理程序中返回结果。这就是为什么结果中的元素未定义

return Promise.resolve(budgetsFormatted)