Sequelize:如何访问 [object Promise] 或从 Promise 返回值? [英] Sequelize: How to access [object Promise] or return value from promise?

查看:128
本文介绍了Sequelize:如何访问 [object Promise] 或从 Promise 返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种情况,我只想在用户登录时访问用户数据.当我不查询数据库时,我有以下代码可以工作.这意味着 var tmp 设置为 YOUR_API_KEY.但是在查询数据库时,我得到了[object Promise].谷歌搜索后,我尝试了不同的解决方案,但没有解决我的问题.

I have a situation where I want to access the user data only if he or she is logged in. I have the following code that works when I'm not querying the database. Meaning the var tmp is set to YOUR_API_KEY. But when querying the database, I get [object Promise]. I tried different solutions after googling around, but nothing seams to solve my question.

var tmp = function() {

   if(req.session.user) {

      return User.findOne({
         where: {
                    id: req.session.user.userID
                },
                include: [
                    { model: Apikey }
                ]
            }).then(function(sqlUser) {
                return sqlUser.Apikeys['0'].kay;
            });

        } else {
            return "YOUR_API_KEY"
        }
}

推荐答案

使用回调"

var tmp = function(callback) {
  if(req.session.user) {
    return User.findOne({
      where: {
              id: req.session.user.userID
            },
            include: [
              { model: Apikey }
            ]
    }).then(function(sqlUser) {
      callback(sqlUser.Apikeys['0'].kay)
    });
  } else {
    callback("YOUR_API_KEY")
  }
}

//now you can use your function like this
tmp(function(apiKey){
  //do something with apiKey e.g.:
  console.log(apiKey)
});

这篇关于Sequelize:如何访问 [object Promise] 或从 Promise 返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆