问题描述
我使用 neDB 创建电子应用程序。
我想创建函数:
const getAllHosts = (db) => {
db.find({},(err,hosts) => {
return hosts
})
}
但是当我调用这个函数时,它返回 undefined,我试图将它更改为 async
,但它没有帮助我。
解决方法
因为您没有从 getAllHosts
返回任何东西。
试试这个
const getAllHosts = (db) => {
return new Promise((resolve,reject) => {
db.find({},(err,hosts) => {
if (err) return reject(err);
resolve(hosts)
})
})
}
getAllHosts().then(hosts => console.log(hosts)).catch(err => console.err(err))
如果您的 db.find
已经返回了一个 promise,您可以尝试这样的操作
const getAllHosts = async (db) => {
try {
const hosts = await db.find({})
return hosts
} catch(err) {
throw err
}
}
getAllHosts().then(hosts => console.log(hosts)).catch(err => console.err(err))