繁体   English   中英

快速响应:以JSON格式发送数组

[英]Express Response: Sending an Array as JSON

我在尝试从后端Express API获取数据时遇到问题。 我也在用mongodb和mongoose。 这是我的代码:代码:

const show = (req, res) => {
  const product = {}
  product.array = new Array()
  console.log(req.cart.product[1])
  for (let i = 0; i < req.cart.product.length; i++) {
  Product.find({_id: ObjectId(req.cart.product[i])},function(err,products){
         if (err) {
            res.sendStatus(500)
        } else {
              product.array.push(products)
              console.log(product.array)
            }
          })
        }
        req.cart.product = product.array
          res.json({
            cart: req.cart.toJSON({ virtuals: true, user: req.user })
          })
    }

Console.logs:

[ [ { _id: 5952b57ea52d092b8d34c6b0,
      name: 'test00000',
      price: 0,
      description: 'test',
      __v: 0 } ] ]
[ [ { _id: 5952b57ea52d092b8d34c6b0,
      name: 'test00000',
      price: 0,
      description: 'test',
      __v: 0 } ],
  [ { _id: 5952b57ea52d092b8d34c6b0,
      name: 'test00000',
      price: 0,
      description: 'test',
      __v: 0 } ] ]

网址回应:

{
    "cart": {
        "_id": "5953b153d2108941d15a7fe9",
        "updatedAt": "2017-06-28T13:38:27.406Z",
        "createdAt": "2017-06-28T13:38:27.406Z",
        "owner": "595153ad6f18427ef38c416b",
        "__v": 0,
        "product": [],
        "id": "5953b153d2108941d15a7fe9",
        "editable": false
    }
}

控制台日志中的所有内容都是我想在products数组中返回的内容,以进行响应,但是当我推送它时不会填充该数组。 有什么想法吗?

您正在尝试在同步代码(例如for循环)中调用异步代码(例如Db查询)。 这就是为什么它在第一次获取数据后就将数据返回给客户端。 您可以asyncpromise.all来解决问题。

var async = require('async')

const show = (req, res) => {
    const product = {}
    product.array = new Array()
    console.log(req.cart.product[1])
    async.each(req.cart.product, function(id, cb){
        Product.find({_id: ObjectId(id)},function(err,products){
          if (err) {
            cb(err)
          } else {
            product.array.push(products)
            console.log(product.array)
            cb()
          }
       })
    }, function(err){
       if (err) {
          return res.sendStatus(500)
       } else {
          req.cart.product = product.array
          return res.json({
             cart: req.cart.toJSON({ virtuals: true, user: req.user })
          })   
       }
    })
}

基于承诺的解决方案:

const show = (req, res) => {
    const product = {}
    product.array = new Array()
    console.log(req.cart.product[1])

    const promises = []     
    req.cart.product.forEach(function(id){
        promises.push(Product.find({_id: ObjectId(req.cart.product[i])}))
    })

    Promise.all(req.cart.product.map(function(id) {
        return Product.find({_id: ObjectId(id)})
    })).then(function(products){
        req.cart.product = product.array
        return res.json({
            cart: req.cart.toJSON({ virtuals: true, user: req.user })
        })
    }).catch(function(err){
        return res.sendStatus(500)
    })
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM