gagle / fulfiller

Always return a Promise

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

fulfiller

Build Status David npm

$ npm install fulfiller

Simple utility that makes a function return a Promise. If no function is provided it always returns a resolved Promise.

import fulfiller from 'fulfiller';

(async () => {
  const fn = (msg: string) => msg;
  const fnPromised = fulfiller(fn);
  const result = await fnPromised('hello');
  console.log(result); // 'hello'
})();

It is very handy when you receive a function as an argument that can be synchronous or return a promise with the result, actually, when you don't care about the synchronicity and just want to execute the function and get the result.

async function foo(fn: () => any | (() => Promise<any>)) {
  return await fulfiller(fn)();
}

console.log(await foo(() => 'sync foo')); // 'sync foo'
console.log(await foo(() => Promise.resolve('async foo'))); // 'async foo'

About

Always return a Promise

License:MIT License


Languages

Language:TypeScript 76.7%Language:JavaScript 23.3%