Initializing multiple dbs with async await at the top level in node

9
May 15, 2019, at 10:00 PM

I understand from a couple of similar questions that to use async await at the top level, it is necessary to wrap up anonymous functions.

I'm trying to initialize several database connections, and can't get the syntax right.

I've tried the following:

let dbs = Promise.all(async () => {
    await sqlite3.open("./db1.sqlite", { Promise }),
    await sqlite3.open("./db2.sqlite", { Promise })
    }
)
let [db_in, db_out] = dbs

which fails with:

evalmachine.<anonymous>:16
let [db_in, db_out] = dbs
                                      ^
TypeError: dbs is not iterable

And

async function init_dbs() {
  const [db_in, db_out, abstract_queue] = await Promise.all([
    sqlite3.open("./db1.sqlite", { Promise }),
    sqlite3.open("./db2.sqlite", { Promise })
  ]);
    let result = await [db_in,db_out]
}

const [db_in, db_out] = init_dbs().then(() => [db_in, db_out])

which returns

evalmachine.<anonymous>:44
const [db_in, db_out] = init_dbs().then(() => [db_in, db_out])
                                                   ^
TypeError: init_dbs(...).then is not a function or its return value is not iterable

What's the right syntax for this?

Answer 1

When using Promise.all, it takes an array of promises and not a callback. It then returns a promise of resolved arrays which you can then finally use.

let db_in, db_out
async function init_dbs() {
  return await Promise.all([
    sqlite3.open("./db1.sqlite", { Promise }),
    sqlite3.open("./db2.sqlite", { Promise })
  ])
}
init_dbs().then(dbs => { 
  [db_in, db_out] = dbs
  // The databases have been initialized, start the application
  start_application()
})
READ ALSO
Connection refused between Node and MongoDB

Connection refused between Node and MongoDB

Getting this error when I try to connect my Node to my MongoDB

21
What claims do refresh token contain?

What claims do refresh token contain?

I am implementing JWT in one of my node appsI am wondering, if there is any definite format/ structure in which a refresh token should be generated?

27
How to get past errors using putParameter with aws-sdk for nodejs in Lambda?

How to get past errors using putParameter with aws-sdk for nodejs in Lambda?

I'm trying to set a parameter using putParameter in the AWS SDK for JavaScript in Nodejs

48
Pass type to function or create type from object

Pass type to function or create type from object

I have function, in which I need to use type, passed like one of function parameters:

28