在nodeJs中,如何让函数成为同步的?

问题描述 投票:0回答:1

我正在用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.js asynchronous async-await
1个回答
0
投票

考虑:下面的函数将无法工作,因为为了让你能够使用 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 将收到 Promise 的结果,所以它必须以下列方式之一被调用。

function async something () {
   const params = {...}
   const res = await serviceFunction(params)
   // do something with res
}

OR

function something () {
   const params = {...}
   serviceFunction(params).then((res) => {
      // do something with res
   })
}
© www.soinside.com 2019 - 2024. All rights reserved.