响应不返回数据

时间:2019-06-05 09:44:00

标签: javascript node.js sequelize.js

我通过保存进餐ID来创建订单,因此尽管使用了async和await,但我仍使用进餐ID从进餐表中获取进餐数据,但现在却出现了问题。它会返回我的响应,其中包含空数据,原因是代码未等待。

我不想使用Promise,因为我的代码库使用async和await。我要保持一致。

static async createOrders(meals, userId, catererId) {
  try {
    const newMeals = JSON.stringify(meals);
    const createdOrder = await Order.create({
      order: newMeals,
      total: 20180,
      caterer_id: 1,
      user_id: userId,
      delivery_status: 0,
    }, {
      raw: true
    });

    const {
      order
    } = createdOrder.dataValues;
    let newOrder = [];
    await order.forEach(async(ord) => {
      const mealId = Object.keys(ord)
      await Meal.findAll({
        where: {
          id: {
            [Op.or]: [...mealId]
          }
        },
        raw: true,
      })
      newOrder = [...res];
    })

    const response = {
      status: 'success',
      message: 'order created',
      data: newOrder,
    };
    return response;
  } catch (error) {
    const response = {
      message: error.message,
      err: true
    };
    throw response;
  }
}
}

响应

   {
    "status": "success",
    "createdOrder": {
        "status": "success",
        "message": "order created",
        "data": []
     }
   }

数据不能为空

1 个答案:

答案 0 :(得分:1)

异步/等待可能无法在forEach循环中按预期方式工作。您应该使用for ... of循环。试试这个:

static async createOrders(meals, userId, catererId) {
  try {
    const newMeals = JSON.stringify(meals);
    const createdOrder = await Order.create({
      order: newMeals,
      total: 20180,
      caterer_id: 1,
      user_id: userId,
      delivery_status: 0,
    }, {
      raw: true
    });

    const {
      order
    } = createdOrder.dataValues;

    let newOrder = [];

    for(let ord of orrd) => {
      const mealId = Object.keys(ord)
      let res = await Meal.findAll({
        where: {
          id: {
            [Op.or]: [...mealId]
          }
        },
        raw: true,
      })
      newOrder = [...res];
    })

    const response = {
      status: 'success',
      message: 'order created',
      data: newOrder,
    };
    return response;
  } catch (error) {
    const response = {
      message: error.message,
      err: true
    };
    throw response;
  }
}

让我知道它是否可以解决您的问题