在继续之前等待异步函数的响应?

时间:2018-06-14 01:49:11

标签: javascript node.js express asynchronous mongoose

假设我想在执行任务之前检查登录用户是否具有管理权限。如果我必须等待来自检查数据库的mongoose函数的响应以了解用户是否具有权限,我该如何异步实现此目的呢?

假设我有这样的用户模型:

  const UserSchema = new Schema({
  username: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  isadmin: {
    type: Boolean,
    default: false
  }
});

然后我创建一个函数来检查用户是否是管理员

function isAdmin(id) {
  let is = false;
  User.findById(id)
    .then(user => {
      if (user) {
        if (user.isAdmin) {
          is = true;
        }
      }
    })
    .catch(err => console.log(err));

  //Now I want to wait for the findById function to resolve before returning this function
  return is;
};

然后假设我想在做一些事情之前检查用户是否是管理员,比如从帖子中删除评论

router.delete("/post/comment/:id"),
  (req, res) => {
    if (!isAdmin(req.user.id)) {
      return res.status(401).json({ notauthorized: "User is not admin" });
    }

    //Go ahead and remove content
  }
);

2 个答案:

答案 0 :(得分:2)

您可以在passportjs中的用户对象或用于doc的包中添加admin密钥。之后,您可以创建一个中间件,并在任何路由中使用它。如果没有看第二个选项。您可以在此中间件中查询用户并检查admin是否为true。希望有意义:))

const requireAdmin = (req, res, next) {
  if (req.user.admin) {
    return next();
  }

  res.sendStatus(401);
}

// Or you can

const requireAdmin = (req, res, next) {
  User.findById(req.user.id)
    .then(user => {
      if (user.admin) {
        return next();
      }
      res.sendStatus(401);
    }).catch(() => res.sendStatus(401))
}


router.delete("/post/comment/:id"),
  requireAdmin,
  (req, res) => {
    // do logc
);

答案 1 :(得分:1)

与EQuimper相似,但https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

async function isAdmin(req, res, next) {
  const user = await User.findById(req.user.id).exec();
  if (!user) {
    next(new Error("User not found"));
    return;
  }
  if (!user.isAdmin) {
    res.status(401).json({ notauthorized: "User is not admin" })
    return;
  }
  next();
};

router.delete("/post/comment/:id", isAdmin, (req, res) => {
  // Do something
});

isAdmin中间件也可以写成:

const isAdmin = async (req, res, next) => {
  const user = await User.findById(req.user.id).exec();
  if (!user) {
    next(new Error("User not found"));
    return;
  }
  if (!user.isAdmin) {
    res.status(401).json({ notauthorized: "User is not admin" })
    return;
  }
  next();
};
相关问题