makepromise
makepromise
can be used to get a Promise from a function with a callback. It will also make sure that the error stack starts at the line where the makepromise
was called.
yarn add -E makepromise
Table Of Contents
API
The package exports a default makepromise
function.
async makePromise(
fn: function(...args, cb),
args: (*[]|*),
): void
Create a promise from a function which accepts a callback as the last argument, and where the callback will be called with 2 arguments: error
and result
. The arguments must be passed either as an array, or a single value.
The example below shows how to use makePromise
with an array of arguments (promisified truncate
) and a single argument (promisified unlink
). The context of the example is 2 methods from a lib to create a temp file, and read data from a file.
async { try // 0. SETUP: create a temp file. const path = await const data = console console console // 1. TRUNCATE to 5 characters. await const data2 = await console // 2. ERASE the temp file. await console catch err console }
Created temp file example/temp.data
Exists: true
Content: "hello-world"
Content: "hello"
Exists: false
async makePromise(
fn: function(...args, cb),
args: (*[]|*),
resolveValue: *,
): void
When resolveValue
is passed as the last argument to the makePromise
function, the returned promise will be forced to resolve with it.
async { try // 0. SETUP: create a temp file. const path = await // 1. UNLINK and return the path to the temp file. const erasedPath = await console catch err console }
Erased: example/temp.data
Binding Methods
Sometimes, it is important to bind methods of instances to their contexts, otherwise they will loose access to this
.
For example. when closing a Writable stream, its close
method must be bound to its instance.
async { try // 0. SETUP: create a temp file. const path = await // 1. CREATE a write stream, and end it with data. const ws = await // 2. CHECK that data has been written. const data = await console // 3. TEAR-DOWN: remove file. await catch err console }
Read file: "example-data"
Error Stack
This modules will make sure that errors are updated to include the stack trace of when makePromise
was called, rather than have the Node's internal error stack or no stack at all.
async { try await catch stack console }
Error: ENOENT: no such file or directory, unlink 'error-test-file'
at /Users/anton/adc/makepromise/example/error-stack.js:6:11
at Object.<anonymous> (/Users/anton/adc/makepromise/example/error-stack.js:10:3)
at Module.p._compile (/Users/anton/adc/makepromise/node_modules/alamode/compile/depack.js:49:18)
at Object.k.(anonymous function).y._extensions.(anonymous function) [as .js] (/Users/anton/adc/makepromise/node_modules/alamode/compile/depack.js:51:7)
Without this functionality, the error stack would not appear.
async { try await { } catch stack console }
Error: ENOENT: no such file or directory, unlink 'error-test-file'
Copyright
(c) Art Deco 2019