【问题标题】:Initializing multiple dbs with async await at the top level in node在节点的顶层使用异步等待初始化多个数据库
【发布时间】:2019-05-15 00:21:00
【问题描述】:

我从a couplesimilar questions 了解到,要在顶层使用async await,需要封装匿名函数。

我正在尝试初始化几个数据库连接,但语法不正确。

我尝试了以下方法:

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

let [db_in, db_out] = dbs

失败:

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

TypeError: dbs is not iterable

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])

返回

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

什么是正确的语法?

【问题讨论】:

    标签: javascript node.js sqlite async-await


    【解决方案1】:

    当使用Promise.all 时,它需要一个promise 数组而不是回调。然后它返回一个已解析数组的承诺,然后您最终可以使用它。

    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()
    })
    

    【讨论】:

    • 谢谢。我的问题中的“顶级”是指在程序的稍后部分对函数调用“做某事”/external/。
    猜你喜欢
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 2018-01-12
    • 2016-12-26
    • 2018-10-01
    • 1970-01-01
    相关资源
    最近更新 更多