【问题标题】:How to get functions to be sychronous, in nodeJs如何在节点 Js 中使函数同步
【发布时间】:2020-05-16 04:41:18
【问题描述】:

我正在用 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】:

    注意事项: 以下函数将不起作用,因为为了让您能够使用 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,您实际上并不需要那里的等待,所以更好的选择是这个。

    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
    }
    

    function something () {
       const params = {...}
       serviceFunction(params).then((res) => {
          // do something with res
       })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      相关资源
      最近更新 更多