从a couple similar的questions了解到,要在顶层使用异步等待,必须包装匿名函数。
我正在尝试初始化多个数据库连接,但语法不正确。
我尝试了以下操作:
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
正确的语法是什么?
答案 0 :(得分:-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()
})