0.1.1 • Published 1 year ago
withdefer.js v0.1.1
WithDefer.js
Defer.js is a wrapper for your functions that tried to implement a similar way to defer
keyword in go.
Installation
with npm
npm install withdefer.js
with yarn
yarn add withdefer.js
Usage
Defer comes with 2 functions:
- withDefer
- withDeferAsync
With Defer
const { withDefer } = require('withdefer.js')
const result = withDefer((defer) => {
defer(function() {console.log("this will print third")})
defer(function() {console.log("this will print second")})
console.log("I will print before all others")
return 1 + 2;
})
console.log("This will print at the end. Result:", result)
With Defer Async
const { withDeferAsync } = require('withdefer.js')
// inside an async function
const result = await withDeferAsync(async (defer) => {
defer(() => new Promise((resolve) => {
console.log("this will print third")
resolve();
}))
defer(() => new Promise((resolve) => {
console.log("this will print second")
resolve();
}))
console.log("I will print before all others")
return 1 + 2;
})
console.log("This will print at the end. Result:", result)
What if a promise rejects?
The function will throw an error