What I want to accomplish:
- Make a request from a database.
- Combine the results of multiple columns into one array.
- Be able to access that array by other functions or methods.
I've accomplished #1 and #2 by making all of the requests to the database in Promise.all() and combining the results into one array.
However, the problem is that I can't access the array in my methods (that I've yet to implement) because the array doesn't contain any content until all the promises have been executed, since it's asynchronous.
Attempts:
1) I tried exporting the array to a different file (in hopes it could extract the array from the promise); however, as you can see below, the only method I found didn't work.
2) The only other solutions I can think of wouldn't work in my situation (like state).
Below is my current progress, I've yet to succeed with requirement number 3. I'm open to any suggestions, even if that means attacking this whole problem a different way then I have.
fileA.js
require('dotenv').config()
const knex = require('knex')
const knexInstance = knex({
client: 'pg',
connection: process.env.DB_URL,
})
let shiftR;
const days = ["monday", "tuesday", "wednesday"];
function dbRequest(day){
console.log("Day: "+day);
return knexInstance.select('shift_time',`${day}`).from('shr');
}
module.exports = Promise.all([
dbRequest(days[0] ? days[0]: null),
dbRequest(days[1] ? days[1]: null),
dbRequest(days[2] ? days[2]: null)
])
.then(results => {
return { shiftR: results } //the array only contains the dates once all the promises
//have been completed
});
FileB.js
const shiftRProm = require('./fileA');
shiftRProm.then(({ shiftR }) => {
console.log(shiftR);
});
I'm stumped on how to fix this. If there's a better way to accomplish what I'm trying to do then I would appreciate the suggestions.
For context, this is what the database ("SHR") looks like, but I don't think this info is needed for the question.
shift_time monday tuesday wednesday (...)
6 AM 1 1 1
7 AM 2 2 2
8 AM 3 3 3
9 AM 3 3 3