what I’m trying to do is:
- loop through array of objects using map function
- run multiple SQL queries according to object
- append result of queries with object
I’m looping through offers which is array of object.I get free_item
and buy_item
which are associated with offer
.I am using knexjs for postgresql database with nodejs
Here’s actual code:
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 }))
The Problem is it is not running in correct sequence.The sequence of the output is
- debug line 1
- debug line 1
- debug line 2
- debug line 2
The correct order should be like this:
- debug line 1
- debug line 2
- debug line 1
- debug line 2
Advertisement
Answer
Using map()
iterates through your array, executing your provided function on each item and storing the results in an array. As you’re passing an asynchronous function, map()
will run the function on each item in parallel and return an array of pending promises, which is then wrapped in the Promise.all
call to wait for them to finish.
If you’re looking to run through your array sequentially, a simple for...of
loop will do:
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-------------------") }