发出Express同步请求并在同一请求中发送多个数据

时间:2019-08-03 06:39:27

标签: javascript node.js express

我想通过一个循环在一个请求中发出一个请求,但是据我所知,它总是异步运行的(我猜是吗?)。 我正在使用Reactjs Redux和Express。

这是我的代码:

profile.jsx

while(i < condition.length) { // say that length = 4
   myData.forEach(item => addingData.push(item))

   // Here I'm calling my request
   this.props.addEmployee(addingData)

   // I wanted to make this 'i' increase ONLY when the request is done.
   // But I'm not sure how to do that
   i++
}

快递请求

router.post("/add-employee", (req, res) => {
    Employee.findOne({ _id: req.id }).then(user => {
       if (user) {

          const newEmp = new Employee({
              nip: req.body.nip,
              name: req.body.name
            })

          // add to employee model. Save employee
            newEmp
              .save()
              .then(user => {
                // Variable for profile
                const newProfile = {}
                newProfile.user = user._id

                // Save profile
                new Profile(newProfile).save()
                console.log("selesai save")

          res.status(200).json(user)
       } else {
          // error
       }
    })
})

这总是返回带有4个副本的最后一个数据,这意味着它将添加四个数据并且全部相同。我如何做到这一点,我读到这是因为请求没有同步运行,但是我该怎么做?

谢谢您的帮助!

更新

正如@Nathan Fries所建议的那样,我创建了一个新的路由器来处理带有对象数组的多个请求。但是我仍然遇到同步问题(我猜是吗?)。这是我的代码:

profile.jsx

for (i; i < this.state.file.length; i++) {
      this.state.file[i].map(item => temp.push(item))

      addData.push({
        nip: temp[0],
        name: temp[1]
      })

      temp = []
    }

// make a request
this.props.addMultipleEmployee(addData)

routes / api / employees.js

// create/add multiple karyawan
router.post(
  "/add-multiple-karyawan",
  passport.authenticate("jwt", {
    session: false
  }),
  (req, res) => {
    let errors
    let isValid
    let newEmp
    let i = 0

    // console.log(req.body) 
    // this req.body value : 
    // [{nip: "nip1", name: "name1"}, 
    //  {nip: "nip2", name: "name2"}]

    for (i; i < req.body.length; i++) {
      isValid = validationEmployee(req.body[i]).isValid
      errors = validationEmployee(req.body[i]).errors

      if (!isValid) {
        return res.status(404).json(errors)
      }

      console.log("checking for sure")
      console.log(req.body[i])
      // The value was still there


      Nip.findOne({ nip: req.body[i].nip }).then(profile => {
        if (profile) {
          return res.status(400).json({
            nip: "NIK tidak valid, karena ini adalah NIK admin. Coba lagi"
          })
        } else {

          // But when it's trying to findOne, the error message said
          // 'nip' are undefined
          Karyawan.findOne({
            nip: req.body[i].nip
          }).then(exists => {
            if (exists) {
              return res.status(400).json({
                nip: "Karyawan telah terdaftar dengan NIK yang sama."
              })
            } else {

              // adding request.body to mongoDB
              newEmp = new Karyawan({
                nip: req.body[i].nip,
                name: req.body[i].name
              })

              // add to employee model. Save employee
              newEmp
                .save()
                .then(user => {
                  // Variable for profile
                  const newProfile = {}
                  newProfile.user = user._id

                  // Save profile
                  new Profile(newProfile).save()
                  console.log("selesai save")

                  res.status(201).json(user)
                })
                .catch(err => {
                  console.log(err)
                })
            }
          })
        }
      })
    }
  }
)

我收到此错误:

TypeError: Cannot read property 'nip' of undefined
[0]     at D:\Kuliah\Semester-7\ptpnx-jombang\routes\api\employees.js:198:32
[0]     at processTicksAndRejections (internal/process/task_queues.js:85:5)
[0] (node:22236) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
[0]     at ServerResponse.setHeader (_http_outgoing.js:464:11)
[0]     at ServerResponse.header (D:\Kuliah\Semester-7\ptpnx-jombang\node_modules\express\lib\response.js:771:10)
[0]     at ServerResponse.send (D:\Kuliah\Semester-7\ptpnx-jombang\node_modules\express\lib\response.js:170:12)
[0]     at ServerResponse.json (D:\Kuliah\Semester-7\ptpnx-jombang\node_modules\express\lib\response.js:267:15)
[0]     at D:\Kuliah\Semester-7\ptpnx-jombang\routes\api\employees.js:247:22
[0]     at processTicksAndRejections (internal/process/task_queues.js:85:5)
[0] (node:22236) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
[0] (node:22236) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process
with a non-zero exit code.

有人说我需要与Async / await或Promise同步吗?但是我不确定该怎么做。我还是Async / await和Promise的新手。

谢谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您为什么不添加一条/add-employees路线来处理多个员工的增加?您可以将它们推送到jsx中的数组,然后一次将它们全部发送。这样可以完全避免async问题。

您还用newEmp而不是const声明了let。您可以通过req.length获得长度,并遍历数组。