javascript - 使用 Array.map 时嵌套的 Promise,使用 Promise.all 但仍然不起作用

标签 javascript arrays node.js mongoose promise

我已经用头撞墙有一段时间了。我有一些 Node 代码,可以提取一堆 googlecalendar 事件,然后将它们映射到不同的对象结构以在我的 web 应用程序中使用...作为其中的一部分,我需要将 google 日历事件中的用户与我的 web 应用程序中的用户进行匹配数据库。代码如下:

router.post('/getCalendar', function(req,res) {  
  // authentication
  var oauth2Client = getOAuthClient();
  var session = req.session;
  oauth2Client.setCredentials({
    access_token: req.user.google.token,
    refresh_token: req.user.google.refreshToken,
    expiry_date: true
  })

  var p = new Promise(function (resolve, reject) {
    // get the next 20 calendar events   
    var calendar = google.calendar('v3');
      calendar.events.list({
        auth: oauth2Client,
        calendarId: 'primary',
        timeMin: (new Date()).toISOString(),
        maxResults: 20,
        singleEvents: true,
        orderBy: 'startTime'
      }, function(err, response) {
        if (err) console.log('err',err)
          // displays all the events
        if (response) console.log('response',response)
        if(response) {
          var events = response.items;
          resolve(events || err);  
        }        
    });

  }).then(function (data) {

    var newdata = data.map(function(item) {
      // create the new object structure and populate with some details
      newObj = {
          _id: item.id,
          _title: item.summary,
          group: [req.headers.group],
          fields: [],
          assignedTo: [],
          google: "calendar",
          googledata: item,
          _category: []
      }

      var extendedFields = {}

      // get the list of attendees
      attendees = item.attendees.map(function(user) {
        var attendee = user.email;
        return attendee;
      })

      // pulls the user information for each attendee using promises
      var promises = attendees.map(function(email) {
        return new Promise(function(resolve, reject) {

          // data is in a mongodb, using mongoose
          User.findOne({'google.email': email}).exec(function (err, user) {
            if (err) return resolve(null);
            resolve(user); //not using reject at all so the Promise.all shouldn't fail
          });
        })
      })

      Promise.all(promises)
        .then(function(value) {
          value.forEach(function(user) {
            if(promise !== null) {
              newObj.assignedTo.push(user);  
            }
          });

          return newObj

      }).catch((error) => {console.log(error)})

  })

  res.json(newdata)
  })

});

我正在使用 Promise.all 等待所有 promise 都已解决,但它似乎在完成第一个之前就移至 data 数组中的下一项。欢迎任何指导。如果需要更多详细信息,请告诉我。

谢谢。

最佳答案

  1. 返回最后一个 Promise.all 的 promise 。

    return Promise.all(promises)
        .then(function(value) {
          value.forEach(function(user) {
            // user !== null ? 
            if(promise !== null) {
              newObj.assignedTo.push(user);  
            }
          });
    
          return newObj
        })
        .catch((error) => {console.log(error)})
    
  2. 在 newdata 上使用 Promise.all。

    Promise.all(newdata)
      .then(function (newObjs) {
        // newObjs is the Array of newObj in your code
        res.json(newObjs);
      })
      .catch(function (err) {
        console.log(err);
      });
    

关于javascript - 使用 Array.map 时嵌套的 Promise,使用 Promise.all 但仍然不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43182161/

相关文章:

javascript - 当用户单击表格第二列的标题时更改第二列的值

javascript - Chrome/V8 不垃圾回收循环引用?

javascript - "(time zone)"在某些机器上 new Date() 可接受的输入,但其他机器则期望 "time zone"

c++ - 诠释 *吨;这个 t[*t] - 类型定义

ios - 检查哪个 ViewController 进行了 segue(来自目标 ViewController)

node.js - 从 Passport-azure-ad.OIDCStrategy 获取 access_token 用作不记名 token

javascript - 在 1 行代码中自定义构造函数

C++,从字符串到字符数组的转换

javascript - 如何根据node.js中的当前时间戳生成带有年份的动态季度数字?

node.js - Sequelize 数据库错误: relation table does not exist