node.js - 如何在nodeJs中使函数同步
问题描述
我正在用 nodeJS 构建一个后端。由于数据库调用是异步的,我想返回它的结果,我必须等待查询结果。但随后我将不得不再次使用 await 使函数异步。是否有可能以某种方式打破这一点并具有同步功能?
我的目标是拥有这样的东西。
function persistenceFunction(params){
// Do something to await without this persistenceFunction having to be async
return await pool.query('SELECT stuff FROM table WHERE a=?;',params);
}
function serviceFunction(params){
validate(params);
// do stuff
return persistenceFunction(params);
}
对于数据库连接,我使用的是 node db 模块。
解决方案
注意事项:以下函数将不起作用,因为为了让您能够使用await
,您必须将您的函数声明为async
function persistenceFunction (params){
// Do something to await without this persistenceFunction having to be async
return await pool.query('SELECT stuff FROM table WHERE a=?;',params);
}
但是由于您要返回pool.query
,因此您实际上并不需要 await 那里,因此更好的选择是这个。
function persistenceFunction (params){
// Do something to await without this persistenceFunction having to be async
return pool.query('SELECT stuff FROM table WHERE a=?;',params);
}
请记住,调用的代码的任何部分serviceFunction
都会收到 aPromise
结果,因此必须以下列方式之一调用它:
function async something () {
const params = {...}
const res = await serviceFunction(params)
// do something with res
}
或者
function something () {
const params = {...}
serviceFunction(params).then((res) => {
// do something with res
})
}
推荐阅读
- javascript - Jest React Native Expo.fx.js 遇到了一个意外的令牌
- r - Return multiple lists with foreach
- sql - 使用数组元素设置变量
- javascript - 我无法获取/显示跨度的输入值(在 IFRAME 中)
- javascript - 导航侦听器中的本机导航错误路由参数
- django - 如何修复 django 中的错误凭据错误
- c# - 如何使用闭包从发出的方法调用 DynamicMethod
- javascript - 有条件地将类应用于列表中的特定项目 Vue.js 3.0
- java - 使用 JWT 授权微服务
- sql - 如何在嵌套的双美元符号交叉表查询中使用 postgres 参数