Last active
August 3, 2017 05:55
-
-
Save suguru03/a5ff2607a5481d23f741a686220ffed1 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
'use stirct'; | |
const assert = require('assert'); | |
const Promise = require('bluebird'); | |
class Connection { | |
constructor() { | |
this._closed = false; | |
} | |
async close() { | |
await Promise.delay(20); | |
console.log('Connection closed'); | |
this._closed = true; | |
} | |
} | |
class LargeObjectManager { | |
constructor(client) { | |
this._client = client; | |
this._closed = false; | |
} | |
async close() { | |
await Promise.delay(100); | |
console.log('LargeObjectManager closed'); | |
assert.strictEqual(this._client._closed, false); | |
this._client = null; | |
this._closed = true; | |
} | |
} | |
function getClient() { | |
return Promise.delay(100, new Connection()).disposer(conn => conn.close()); | |
} | |
function getLOM(client) { | |
return Promise.delay(20, new LargeObjectManager(client)).disposer(lom => lom.close()); | |
} | |
function using(...args) { | |
const handler = args.pop(); | |
const l = args.length; | |
let i = 0; | |
return execute(args[i]); | |
function execute(func, arg) { | |
return Promise.using(func(arg), data => { | |
return ++i === l ? handler(data) : execute(args[i], data); | |
}); | |
} | |
} | |
async function execute() { | |
const obj = { result: true }; | |
const res = await using(getClient, getLOM, client => { | |
console.log(client); | |
return Promise.delay(10, obj); | |
}); | |
console.log(res); | |
assert.strictEqual(res, obj); | |
} | |
execute(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment