环回findone函数



我在应用程序的服务器端使用环回,从数据库中获取和验证数据。我使用的是带有回调函数的findOne方法。我想在执行findone函数后立即运行回调函数,我编写的代码正在运行,但我想避免使用异步等待。还有其他选择吗?

我尝试了

function validId(req) {
const filter = {
where: {
ID: req.id,
}
};
//
const result = await model.findOne(filter);
if (result) {
return true;
} else {
return false;
}
}
module.exports = function () {
return async function validateTenant(req, res, next) {
var id = false;
if (req.url.includes("XYZ")) {
id = await validId(req)
}
//
if (id || !req.url.includes("XYZ")") {
next();
} else {

res.writeHead(404, { "Content-Type": "text/html" });
var html = fs.readFileSync(
"error.html"
);
res.end(html);
}
};
};

您可以使用promise 的.then()函数

model.findOne(filter).then((result)=>{
//execute the rest of the function that need to be executed after the findOne.
});
// The code will continue to execute while model.findOne is doing it's thing.

但是,如果您想在不使用await.then的情况下等待FindOne给出结果,除非您制作findOne的包装器或BDD包具有同步findOne,否则这是不可能的

最新更新