import { default } from "https://deno.land/x/froebel@v0.18.0/promisify.ts";
Turns a function accepting a callback into a function returning a promise.
You can specify in which parameter (if any) the callback expects to receive
a result and in which it expects an error.
Pass null
to resultIndex
or errorIndex
if no result or errors are
passed to the callback. By default the first argument passed to the callback
is interpreted as result and none of the arguments as error (if the function
accepting the callback throws or rejects, that will still result in the
promisified function rejecting).
The callbackFirst
property allows passing additional parameters after the
callback and callbackLast
will pass additional parameters before the
callback.
Examples
Example 1
Example 1
const notify = (cb: (msg: string) => void) => { msg('something') }
const waitForMessage = promisify(notify)
await waitForMessage() // -> 'something'
// here result is passed at index 1 and errors at index 0.
const callbackAPI = (cb: (error?: Error, data?: unknown) => void) => {}
const asyncAPI = promisify(callbackAPI, 1, 0)
Example 2
Example 2
const sleep = promisify(setTimeout).callbackFirst
await sleep(200)
Example 3
Example 3
const fs = require('node:fs');
const stat = promisify(fs.stat, 1, 0).callbackLast
try {
const stats = await stat('.');
console.log(`This directory is owned by ${stats.uid}`);
} catch (err) {
console.error(err)
}