@micromint1npm/aperiam-perferendis-suscipit
Make a callback-based or promise-based functions to support both promises and callbacks. Uses the native promise implementation. with typescript support.
![License](https://img.shields.io/npm/l/@micromint1npm/aperiam-perferendis-suscipit.svg)
Installation
npm i @micromint1npm/aperiam-perferendis-suscipit
Import or Require
import ppc from "@micromint1npm/aperiam-perferendis-suscipit";
OR
import {fromCallback,fromPromise} from "@micromint1npm/aperiam-perferendis-suscipit";
OR
const ppc = require("@micromint1npm/aperiam-perferendis-suscipit");
OR
const fromCallback = require("@micromint1npm/aperiam-perferendis-suscipit");
OR
const fromPromise = require("@micromint1npm/aperiam-perferendis-suscipit");
Here is an example usage of fromCallback
function:
Suppose you have an asynchronous function readFile that reads a file and takes a callback as the last argument:
function readFile(filename, callback) {
}
You can convert this function to return a Promise with fromCallback
function as follows:
import {fromCallback} from "@micromint1npm/aperiam-perferendis-suscipit";
const readFilePromise = fromCallback(readFile);
readFilePromise(filename)
.then((data) => console.log(data))
.catch((err) => console.error(err));
readFilePromise(filename, (err, data) => {
if (err) {
console.error(err);
} else {
console.log(data);
}
});
This allows you to use the same function in either Promise-based or callback-based code.
Here is an example usage of fromPromise
function:
Suppose we have a function getUser that returns a promise:
function getUser(userId) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (userId === '123') {
resolve({ id: '123', name: 'John Doe' });
} else {
reject(new Error('User not found'));
}
}, 100);
});
}
We can use fromPromise
to create a function that can be called with a callback:
import {fromPromise} from "@micromint1npm/aperiam-perferendis-suscipit";
const getUserCallback = fromPromise(getUser);
getUserCallback('123', (err, user) => {
if (err) {
console.error(err);
} else {
console.log(user);
}
});
In the above example, the getUserCallback function accepts a callback as its last argument. If a callback is provided, it calls the original getUser function with the provided arguments and passes the result or error to the callback. If no callback is provided, it returns a promise.
We can also call getUserCallback without a callback to get a promise:
getUserCallback('123')
.then(user => console.log(user))
.catch(err => console.error(err));
License
@micromint1npm/aperiam-perferendis-suscipit is licensed under the MIT License.