Last active
August 27, 2016 23:49
-
-
Save carlosrymer/8ee94a22dba38788fb167d3afde3ea91 to your computer and use it in GitHub Desktop.
This is an example of how to use the disposer feature in Bluebird.js to immediately destroy a database connection once it's used.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Let's assume that we're using the mysql module for Node.js in this example. | |
const mysql = require('mysql'); | |
// We'll use Bluebird.js instead of the native Promise | |
const Promise = require('bluebird'); | |
// Now, let's create a function that returns a promise that resolves to a database connection | |
function getConnection() { | |
return Promise.try(() => Promise.promisifyAll(mysql.createConnection({}))) // We're assuming default options here | |
.disposer(connection => connection.destroy()); // Disposer will be called once getConnection resolves | |
} | |
// Now, let's use our function defined above with Promise.using | |
return Promise.using(getConnection(), connection => connection.queryAsync()); // Here we make our query, and once it's resolved, our disposer's callback will be executed, destroying the connection |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment