javascript - 进行 Express 同步请求并在同一个请求中发送多个数据

标签 javascript node.js express

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

这是我的代码:

配置文件.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 的建议,我创建了一个新路由器来处理带有对象数组的多个请求。但我仍然遇到同步问题(我猜?)。这是我的代码:

配置文件.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 的新手。

谢谢你的帮助!!

最佳答案

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

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

关于javascript - 进行 Express 同步请求并在同一个请求中发送多个数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57336079/

相关文章:

javascript - 用于 Jquery 开发的 IDE

javascript - 从外部文件调用外部 JS 函数

javascript - 从框中选择值时检测输入字段的变化

linux - 在亚马逊服务器上执行 bash 时出现错误 [错误 : spawn EACCES], bash 在正确的路径中

node.js - Webpack 因 Node FFI 和 Typescript 失败 - 动态需要错误

node.js - Express:使用 websocket 共享 session

javascript - react native : How to define a javascript class

node.js - 如何使用 React Router 从 React.js 的子路径修复错误的代理重定向?

javascript - 使用 Multer 上传文件,不知道他们的字段名

node.js - typescript express 中间件