0

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?

Mittenchops
  • 18,633
  • 33
  • 128
  • 246

1 Answers1

-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()
})
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
  • Thank you. By “top level” in my question, I mean to have the “do something” /external/ to the function call, later in the program. – Mittenchops May 14 '19 at 16:15