简体   繁体   中英

How to pass variable through promise chain using finally

I am trying to build a log for an Express API , however am having issues getting the data to log out.

I can log the original req and res objects in the finally block, but am not sure how I would access the SQL response .

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

router.get("/express-route", (req, res) => {
  sql.connect(config.properties).then(pool => {
    return pool.request()
      .input('username', sql.NVarChar(32), req.params.username)
      .execute('do_something_with_username')
      .then(response => res.send(response) // pass this response
      .catch(err => res.send(err))
      .finally(() => {
        console.log('response', response)  // to here
        sql.close()
      })
  })
}

How would I take the response from the first then block and pass it to the finally block to be used in another function?

A finally callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected. This use case is for precisely when you do not care about the rejection reason, or the fulfillment value, and so there's no need to provide it. ( mdn )

Instead, simply use .then :

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

router.get("/express-route", (req, res) => {
  sql.connect(config.properties).then(pool => {
    return pool.request()
      .input('username', sql.NVarChar(32), req.params.username)
      .execute('do_something_with_username')
      .then(response => {res.send(response); return response;}) // pass this response
      .catch(err => res.send(err))
      .then(response => {
        console.log('response', response)  // to here
        sql.close()
      })
  })
}

You can, in fact, simplify things by writing your code within an async function

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

router.get("/express-route", (req, res) => {
  sql.connect(config.properties).then(async pool => {
    try {
        const response = await pool.request()
                         .input('username', sql.NVarChar(32), req.params.username)
                         .execute('do_something_with_username');

        // do another request
        const otherResponse = await pool.request() ... ;

        res.send(response);
    } catch (err) {
        res.send(err);
    } finally {
        sql.close();
    }
  })
}

This lets you write code in a more linear manner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM