Reputation: 105
I have a program that depending on the size of an array that is being sent from the front end then I have to loop through making knex call to a database then return those values to the front end.
I have tried what some other people have suggested using Promise.all() and the map() function such as:
const req=Json.parse(datafromFE)
const neededvar={
result1="",
result2=[]
}
var call1=knex.select('field1').from('Table1').then(result=>{neededvar.result1=result});
function getData(current,i,knex){
knex.select('data').from('table').where('data','=',current.field)
.then((result)=>{
neededvar.result2[i]=result*neededvar.result1
return(neededvar.result2)
})
}
Promise.all([call1,req.map((current,i)=>{getData(current,i,knex)}])
.then((values)=>{
console.log(values)
e.returnValue=neededvar//using electron ipcRenderer I believe is similar to
//vanilla nodejs backend res.json('placedatahere')
//so just think about
//res.json(neededvar)
})
however,when I run the call the console.log(values) returns undefined for the array map calls but not for the first knex select call as here:
console.log(neededvar)
//[result1,undefined,undefined...]
I have tried to check if its my knex call, doing so by just calling the call1 function inside the map but still returns undefined.
var call1=knex.select('field1').from('Table1')
Promise.all(req.map((current,i)=>{call1}).then((result)=>{
console.log(result)
})
//output:[undefined,...,undefined]
I could just call the API from the front end several times but I just though this would be the most efficient way .If there is any guidance that can be given I would appreciate it much
-------Edit-------
Must remember to add all returns to all functions
function getData(current,i,knex){
knex.select('data').from('table').where('data','=',current.field)
.then((result)=>{
neededvar.result2[i]=result*neededvar.result1
return(neededvar.result2)
})
}
should really be
function getData(current,i,knex){
return(knex.select('data').from('table').where('data','=',current.field)
.then((result)=>{
neededvar.result2[i]=result*neededvar.result1
return(neededvar.result2)
}))
}
the same goes to the other knex call
Upvotes: 0
Views: 1545
Reputation: 7654
The main issue is that the function you pass to .map
returns undefined
:
Promise.all([call1,req.map((current,i)=>{getData(current,i,knex)}])
You probably meant:
Promise.all([
call1,
...req.map((current,i) => getData(current,i,knex)
])
This will combine the first query with the array of queries generated out of req
.
You should also return the promise from getData
:
function getData(current,i,knex){
knex.select('data').from('table').where('data','=',current.field)
should be:
function getData(current,i,knex){
return knex.select('data').from('table').where('data','=',current.field)
Upvotes: 1