【问题标题】:Proper Javascript promise construction using finally()使用 finally() 构建正确的 Javascript 承诺
【发布时间】:2019-07-10 18:07:57
【问题描述】:

我正在构建一个使用 mssql 包构建的 Express API。

如果我不调用sql.close(),则会收到以下错误:

错误:全局连接已存在。先调用sql.close()。

我想让端点易于遵循和维护,并喜欢使用finally 承诺模式的以下模式。

const sql    = require("mssql")
const config = require("../config")

sql.connect(config.properties).then(pool => {
  return pool.request()
    .execute('chain')
    .then(response => {
      res.send(response['recordsets'][0][0]['response'])
    })
    .catch(err => res.send(err))
    .finally(sql.close())
})

但是,这会产生以下错误:

{ “代码”:“ENOTOPEN”, “名称”:“连接错误” }

以下代码有效,但在同一个函数中多次定义sql.close 似乎有点笨拙。

sql.connect(config.properties).then(pool => {
  return pool.request()
    .execute('chain')
    .then(response => {
      res.send(response['recordsets'][0][0]['response'])
      sql.close()
    })
    .catch(err => {
      res.send(err)
      sql.close()
    })
})

在使用res.send 发送响应或错误后,有没有办法调用sql.close 作为承诺链的一部分?

【问题讨论】:

    标签: javascript express promise


    【解决方案1】:

    .finally 接受函数,你传递函数的结果

    sql.connect(config.properties).then(pool => {
      return pool.request()
        .execute('chain')
        .then(response => {
          res.send(response['recordsets'][0][0]['response'])
        })
        .catch(err => res.send(err))
        .finally(() => sql.close()) // FIX HERE
    })
    

    【讨论】:

    • 或者只是.finally(sql.close)
    • @TheReason .finally(sql.close) 你读过为什么这个速记有效吗?
    • @TheReason 这可能需要绑定该方法,否则它会丢失其this 上下文
    猜你喜欢
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 2021-12-12
    • 2020-06-09
    相关资源
    最近更新 更多