首页 > 解决方案 > 如何在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 模块。

标签: node.jsasynchronousasync-await

解决方案


注意事项:以下函数将不起作用,因为为了让您能够使用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
   })
}

推荐阅读