在我的 user.js 文件中,我有一个异步函数来从数据库中检索头像位置,如下所示:
async findavatar(username) {
const sql = `SELECT image FROM users WHERE user = "${username}";`
const db = await sqlite.open(dbName)
const location = await this.db.get(sql)
await db.close()
console.log(location)
return location
}
我在 index.js 文件中调用它:
router.get('/', async ctx => {
try {
if(ctx.session.authorised !== true) return ctx.redirect('/login?msg=you need to log in')
const data = {}
const user = await new User(dbName)
const currentuser = ctx.session.loggeduser
const avatarlocation = user.findavatar(currentuser)
console.log('location of avatar:' + avatarlocation)
if(ctx.query.msg) data.msg = ctx.query.msg
await ctx.render('newarticle', {location: currentuser })
} catch(err) {
await ctx.render('error', {message: err.message})
}
})
用户文件中的 console.log 工作并显示位置,但是当我到达 index.js 文件并运行它时,它给出了一个 promise 。 当我运行页面以检索位置时,我得到了 [object Promise],如何让它显示从数据库中提取的值?
最佳答案
The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
你可以阅读它here.
您需要调用 .then()
来解析 Promise。
例子:
avatarlocation.then(function(value) {
console.log(value);
});
关于javascript - 如何让nodejs返回对象 promise 以外的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58914713/