Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Global 'server' variable becomes undefined? #191

Open
radiolondra opened this issue Dec 27, 2022 · 1 comment
Open

Global 'server' variable becomes undefined? #191

radiolondra opened this issue Dec 27, 2022 · 1 comment

Comments

@radiolondra
Copy link

radiolondra commented Dec 27, 2022

I'm using a function to open the database and try to use the assigned server variable in other functions:

var server;

function OpenDB() {
  db.open({
      .....
  }).then(function(s) {
    server = s;
  });
}

function DoSomethingInDB() {
  console.log("Server var:", server); <<<< undefined
  server.mytable.count().then(function(ct) {  <<<error: Cannot read properties of undefined (reading 'mytable')
    ...
  });
}

....

OpenDB();
DoSomethingInDB();

My database is successfully created in OpenDB().
Unfortunately, it seems that the global server var becomes undefined outside the OpenDB function.
From documentation:

A connection is intended to be persisted, and you can perform multiple operations while it's kept open

But I didn't close it. Bah?
For sure I'm doing something wrong. Can you help me?
Thanks.

@radiolondra radiolondra changed the title Global Server variable became undefined? Global 'server' variable became undefined? Dec 27, 2022
@radiolondra radiolondra changed the title Global 'server' variable became undefined? Global 'server' variable becomes undefined? Dec 27, 2022
@SpicyCatGames
Copy link

SpicyCatGames commented Jul 25, 2023

Hey, I do not think this is an issue. Your then() is likely executing after DoSomethingInDB() so server is not even assigned to yet. To avoid this, in an async function, you need to await db.open().

Try this for example:

var server;

async function OpenDB() {
    await db.open("somedb").then(function (s) {
        server = s;
    });
}

function DoSomethingInDB() {
    console.log("Server var:", server);
    server.mytable.count().then(function (ct) {

    });
}

async function Exec(){
    await OpenDB();
    DoSomethingInDB();
}

Exec();

Anyway, this is how promises work and there is nothing wrong with the library itself in the example you provided.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants