如何在javascript循环(map)内运行SQL查询?

如何在javascript循环(map)内运行SQL查询?,sql,node.js,postgresql,async-await,Sql,Node.js,Postgresql,Async Await,我想做的是: 使用映射函数在对象数组中循环 根据对象运行多个SQL查询 将查询结果附加到对象 我正在循环浏览一系列的优惠,这是一个对象数组。我得到了与优惠相关联的免费项目和购买项目。我正在使用knexjs for postgresql数据库和nodejs 下面是实际代码: offers = await Promise.all(offers.map(async offer => { free_item_id = await db("offer_free_item

我想做的是:

  • 使用映射函数在对象数组中循环
  • 根据对象运行多个SQL查询
  • 将查询结果附加到对象
我正在循环浏览一系列的优惠,这是一个对象数组。我得到了与
优惠
相关联的
免费项目
购买项目
。我正在使用knexjs for postgresql数据库和nodejs

下面是实际代码:

offers = await Promise.all(offers.map(async offer => {
        free_item_id = await db("offer_free_items").where({"offer_free_items.offer_id":offer.id}).select(["item_id"]).first()
        console.log("-----------------debug line 1------------------")

        buy_item_id = await db("offer_buy_items").where({"offer_buy_items.offer_id":offer.id}).select(["item_id"]).first()
        console.log("-----------------debug line 2-------------------")

        offer["free_item_id"] = get_item_id
        offer["buy_item_id"] = buy_item_id
        return offer
}))
问题是它没有以正确的顺序运行。输出的顺序是

  • 调试行1
  • 调试行1
  • 调试行2
  • 调试行2
  • 正确的顺序应如下所示:

  • 调试行1
  • 调试行2
  • 调试行1
  • 调试行2
  • 使用
    map()
    遍历数组,对每个项执行提供的函数,并将结果存储在数组中。在传递异步函数时,
    map()
    将对每个项并行运行函数,并返回一个挂起承诺数组,然后将其包装在
    承诺中。所有调用都将等待它们完成

    如果您希望按顺序运行数组,则可以使用一个简单的
    for…of循环:

    for (let offer of offers) {
        offer["free_item_id"] = await db("offer_free_items").where({"offer_free_items.offer_id":offer.id}).select(["item_id"]).first()
        console.log("-----------------debug line 1------------------")
    
        offer["buy_item_id"] = await db("offer_buy_items").where({"offer_buy_items.offer_id":offer.id}).select(["item_id"]).first()
        console.log("-----------------debug line 2-------------------")
    }
    
    使用
    map()
    遍历数组,对每个项执行提供的函数,并将结果存储在数组中。在传递异步函数时,
    map()
    将对每个项并行运行函数,并返回一个挂起承诺数组,然后将其包装在
    承诺中。所有调用都将等待它们完成

    如果您希望按顺序运行数组,则可以使用一个简单的
    for…of循环:

    for (let offer of offers) {
        offer["free_item_id"] = await db("offer_free_items").where({"offer_free_items.offer_id":offer.id}).select(["item_id"]).first()
        console.log("-----------------debug line 1------------------")
    
        offer["buy_item_id"] = await db("offer_buy_items").where({"offer_buy_items.offer_id":offer.id}).select(["item_id"]).first()
        console.log("-----------------debug line 2-------------------")
    }
    

    你很完美。节省了我的时间,你太完美了。节省了我的时间。