Nest.JS中的Sequelize Query在返回之前无法解析

时间:2019-04-17 22:53:09

标签: node.js promise sequelize.js nestjs sequelize-typescript

我有一个函数,该函数从数据库获取订单,从响应创建对象,从db获取所有行项目的响应,并在这些项目上循环以获取详细记录。我遇到的问题是,即使我试图等待子查询的响应,整个函数也会返回。

代码如下:

public async getOrderById(orderId:string) {
    const order: [any] = await this.dbInstance.query('exec getOrder :orderID' {replacements: {orderID: orderId}, type: sequelize.QueryTypes.SELECT});
    const orderLines: [any] = await this.dbInstance.query('exec getOrderLines :orderID' {replacements: {orderID: orderId}, type: sequelize.QueryTypes.SELECT});

    const orderArray: any = order.map((o) => { 
         return {
            orderId,
            customerId: o.CustomerID
            total: o.total,
            lines: []
          };
    });

    const orderResponse: Order = orderArray[0];

    orderLines.forEach(async (orderLine) => { 
         let addItem: any;
         addItem = {
                itemNumber: orderLine.itemNumber,
                quantity: orderLine.quantity,
                unitPrice: orderLine.unitPrice,
                orderLineDetails: []
         };

        await this.dbInstance.query('exec getLineDetails :orderLineId{replacements: {orderLineId: orderLine.orderLineId}, type: sequelize.QueryTypes.SELECT})
         .then( (details) => { 
             details.forEach((detail) => {
                addItem.orderLineDetails.push({
                    name: detail.name,
                    value: detail.val
                });
             });
         });

        orderResponse.orderLines.push(addItem);
    });

    return orderResponse;

}

因此,代码将进入订单行的forEach中,创建添加项,但随后它将在等待创建orderLineDetails的结果并将其添加到orderLineDetails数组之前推送addItem。如果我让整个过程都运行起来,则在响应返回之后,带有orderLineDetails的推送的断点将运行一秒钟。

我想念什么?

1 个答案:

答案 0 :(得分:1)

所以问题是我用来执行非异步映射(forEach)的方法,以及修改循环中的基础集合。

我最终做了这个改变:

const orderLinePromises = orderLines.map(async (orderLine) => { 
    let addItem : any;

     addItem = {
            itemNumber: orderLine.itemNumber,
            quantity: orderLine.quantity,
            unitPrice: orderLine.unitPrice,
            orderLineDetails: []
     };

     const details = await this.dbInstance.query('exec getLineDetails :orderLineId{replacements: {orderLineId: orderLine.orderLineId}, type: sequelize.QueryTypes.SELECT});
      addItem.orderLineDetails = details.map((detail) => {
            return {
               name: detail.name,
               value: detail.val,
            };
      );

     return addItem;

});

orderResponse.orderLines = await Promise.all(orderLinePromises);

return orderResponse;