首页 > 解决方案 > 是否可以从 .then 函数导出数据?

问题描述

我正在使用 mssql 模块处理 Node 和 MSSQL Server。使用 Promise 时,我想从 .then 函数导出或返回数据。这是可能的还是有任何解决方法?

getDb = function(){

// This code establishes connection to SQL Server

  const conn = new sql.ConnectionPool(dbConfig);
  const req = new sql.Request(conn)
  conn.connect()
  .then(function getData (req) {

// This code makes query to SQL Server

      req.query("SELECT * FROM USER")
      .then(function(res){

      console.log(res) // logs Correct User
      module.exports.user = res // logs undefined in main.js

      })
      .catch((err) => console.log(err))
    }
  )
  .catch(function (err) {
      console.log(err);
  });
}
getDb()

任何帮助是极大的赞赏!

标签: node.jssql-serverasynchronouses6-promise

解决方案


这是一种简单的方法,您可以导出 getDb 函数并将其导入并使用到数据中:

exports.getDb = () => {

    return new Promise((resolve, reject) => {
      const conn = new sql.ConnectionPool(dbConfig);
      const req = new sql.Request(conn)
      conn.connect().then(req => {
        return req.query("SELECT * FROM USER")
      }).then(res => {
        return resolve(res);
      }).catch(err => {
        console.log(err)
      })
    })
}

推荐阅读