javascript - 如何让nodejs返回对象 promise 以外的东西

标签 javascript node.js

在我的 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/

相关文章:

javascript - 如何更改 DataTables 上的 sLengthMenu 位置?

javascript - Mocha 测试 : 'TypeError: undefined not a function' at Test. serverAddress

mysql - 从表中选择最新数据

javascript - 这是在 javascript/node js 中编写处理错误处理 then-catch 或 try-catch 的最佳实践

javascript - 如何使用 jquery 循环遍历具有嵌套对象的数组?

javascript - 添加缩小的 js、css 和非缩小的 js、css 是有益的吗?

javascript - 使用变量引用创建 react 状态名称?

php - 将博客与 heroku 上的 Node.js 应用程序集成

node.js - req.session 通常在路由中未定义(connect-redis 用作存储)

值更改时的Javascript文本框调用事件