ExpressJS回调功能 - 正确实现

时间:2017-03-04 11:15:11

标签: javascript node.js rest express

所以我有以下情景 -

我有关于创建发票的帖子请求。

我将以下.json发送给请求:

{
  invoice: {
    client_id: 1,
    status: 'Open'
  },
  invoice_products: [
    {
      product_id: 1,
      quantity: 2
    },
    {
      product_id: 3,
      quantity: 55
    }
  ]
}

我首先在后端验证数据,之后我按照以下步骤进行操作 -

1)我在invoice_products上进行for循环,并尝试从每个产品的数据库中读取价格。它看起来像这样 -

// Let's retrieve price for the invoice
let price = 0;
for (let invoice_product_nr = 0; invoice_product_nr < req.body.invoice_products.length; invoice_product_nr++) {
    products.getById(req, req.body.invoice_products[invoice_product_nr].product_id, next);
    console.log(req.productData);
    price += req.productData.data.price;
}

我的products.getById()函数看起来像这样 -

function getById(req, id, next) {
    products.getOne(id)
        .then((data) => {
            // Check if product exists
            if (data === undefined) {
                const message = {
                    errors: response.errors.general.notFound
                };
                next();
            }

            // Everything is fine - return products data
            const message = {
                success: response.success.general.dataReturned,
                data
            };

            req.productData = message;

            next();

        })
        .catch((error) => {
            console.log(error);
            // Unexpected error happened, return error message.
            next();
        });
}

这里的第一个问题是它没有req.productData设置,当它从getById函数返回时,我怎么可能解决这个问题?

2)之后,我使用传递的发票数据进行数据库插入 -

// Let's insert invoice in database
invoices.insert(invoice)
    .then((result) => {
        // Let's insert invoice products
        for (let invoice_product_nr = 0; invoice_product_nr < req.body.invoice_products.length; invoice_product_nr++) {
            let invoice_product = {
                invoice_id: result[0],
                product_id: req.body.invoice_products[invoice_product_nr].product_id,
                quantity: req.body.invoice_products[invoice_product_nr].quantity
            };
            invoice_products.insert(invoice_product)
                .then(() => {
                    next();
                })
                .catch((error) => {
                    console.log(error);
                    // There is an internal error in database
                    return response.reportMessage(500, undefined, res);
                });
        }

        // invoice has been added, notify user
        const message = {
            success: response.success.general.dataAdded,
        };
        return response.reportMessage(201, message, res);
    })
    .catch((error) => {
        console.log(error);
        // There is an internal error in database
        return response.reportMessage(500, undefined, res);
    }); 

问题在于我不喜欢插入状态网络的for循环,我打算将其切换到knex批处理请求(你的建议?),这里的第二个问题是response.reportMessage res.send(),我收到headers already sent次错误。

干杯!

0 个答案:

没有答案