首页 > 解决方案 > Promise.resolve 与数组

问题描述

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

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

我将它包装在一个Promise.all块中,然后将所有这些已解决的承诺添加到另一个数组中。这个最终数组包含 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)

标签: javascriptarrayspromise

解决方案


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

return Promise.resolve(budgetsFormatted)

推荐阅读