Ok, I give up on searching. Can anyone help me please with this whole JavaScript async behaviour? I am relativly new to JavaScript. What I want to achieve:
Open a connection to my sql database. Store that connection to a variable. Use this connection in my following code.
Problem: The opening of the connection is async, the code runs on and my connection variable is undefined
.
So, how do I wait OUTSIDE of async functions that these functions are finished?
My Code:
'use strict';
const mssql = require('mssql');
let config = {...} // everything works inside here
let connection;
let connectFunction = async () => {
return mssql.connect(config);
};
let result;
connectFunction().then(resolve => {
connection = resolve;
connection.request().query('SELECT * FROM users').then(result => {console.log(result);});
// This would work, BUT I dont want to be stuck inside a thenified or async function
});
connection.request().query('SELECT * FROM users').then(result => {console.log(result);});
// This does not work, because the connectFunction would not be awaited.
I want to reuse the open connection later, so it would be stupid to work inside the connectFunction().then
, because that would open the connection on every query.
How can I solve this the best way?