A declarative way of doing asynchronous programing with Typescript.

Overview

Deasyncify

A declarative way of doing asynchronous programing with Typescript.

Overview

Getting started

Deasyncify is a utility library which builds on top of Typescript's Promise api and simplifies handling promises and async functions. The goal of this library is to help make handling asychronous Typescript code more declarative withoud having to wrap code in a try-catch blockcode (which makes your code more cleaner) and without losing type definition on the return types of the values of resolved promises or async function trying to write a custom wrapper for yourself (yes we implemented that too). Imagine writing your own custom async wrapper for every single new project (that's pretty much a drag).

import axios from 'axios';
import Deasyncify from 'deasyncify';

const doSomething = async () => {
    const [expectedValue, error] = await Deasyncify.watch(axios.get(url))

    if(error) throw error

    return expectedValue
}

Issues

This library is meant to work on all nodejs enviroments. If any issue or bug is found in whatever enviroment you are on, feel free to report it to issues and we'll address it as fast as we can.

Installation

Using yarn

$ yarn add deasyncify

Using npm

$ npm install deasyncify

Usage

Deasyncify is a utility class which currenctly comprises of watch, watchAll and watchSettled methods which we'll look into below

Methods

watch

Deasyncify.watch is used to handle a single asynchorous function or promise.

Definitions

  • watch = <T> (asynParam: Promise<T> | (() => Promise<T>)) => Promise<[T | null, any]>
  • Args
    • asyncParam: Promise<T> | (() => Promise<T>)
  • Expected output:
    • expectValue: T | null
    • error: any

usage

watch takes in on argument (which could be either a promise or an async function or a function that returns a promise) executes it and returns an array of two values; expectedValue and error. expectedValue being the value return from your asynchronous code (you can name this anything) and error being any errors which running your asynchronous code (you can name this anything as well). error would be undefined if the asyncParam runs successfully but if asyncParam fails, error would be defined an expectedValue would be undefined.

Example

import { Request, Response, Next } from "express";
import prisma from "prisma";
import Deasyncify from "deasyncify";

export const getUser = async (req: Request, res: Response, next: Next) => {
    const [user, userFindError] = await Deasyncify.watch(this.prisma.users.findOne({
        where: { userId: req.user.id }
        }));

    if(userFindError) return next(userFindError);

    res.json(user);
};

watchAll

Deasyncify.watchAll is used to handle a bunch of asynchorous function or promise "concurrently".

Definitions

  •  watchAll = <
      J,
      T extends Awaited<J>,
      G = T extends () => any ? Awaited<ReturnType<T>> : T> (asyncArr: J[]) => Promise<[G[] | null, any]>
    
    
  • Args

    • asyncParam: (Promise<T> | (() => Promise<T>))[]
  • Expected output:

    • expectValues: T[] | null
    • error: any

usage

watchAll takes in on argument (which could be an array of an asyncParam (a promise or an async function or a function that returns a promise)) executes it and returns an array of two values; expectedValue and error. expectedValues being the value return from your asynchronous code (you can name this anything) and error being any error that occur while running your asynchronous code (you can name this anything as well). if any of the asyncParam in the arr fails, expectedValues would be null and error would be defined. An alternative to this is watchSettled method which doesn't have this behaviour.

Example

import { Request, Response, Next } from "express";
import prisma from "prisma";
import Deasyncify from "deasyncify";

export const getUserItems = async (req: Request, res: Response, next: Next) => {
    const [userItems, userItemsFindError] = await Deasyncify.watchAll([
        this.prisma.cars.findOne({where: { ownersId: req.user.id } }),
        this.prisma.phones.findOne({ where: { ownersId: req.user.id }}),
        this.prisma.pets.findOne({ where: { ownersId: req.user.id }})
        ]);

    if(userFindError) return next(userItemsFindError);

    res.json(userItems);
};

watchSettled

Deasyncify.watchSettled is used to also handle a bunch of asynchorous function or promise "concurrently".

Definitions

  •  watchSettled = <
      J,
      T extends Awaited<J>,
      G = T extends () => any ? Awaited<ReturnType<T>> : T> (asyncArr: J[]) => Promise<[G[], any[]]>
    
    
  • Args

    • asyncParam: (Promise<T> | (() => Promise<T>))[]
  • Expected output:

    • expectValues: T[] | null
    • errors: any[]

usage

watchAll takes in on argument (which could be an array of an asyncParam (a promise or an async function or a function that returns a promise)) executes it and returns an array of two values; expectedValue and error. expectedValues being the value return from your asynchronous code (you can name this anything) and error being an arr of errors which running your asynchronous code (you can name this anything as well). unlike watchAll which fails if one of the asyncArr elems fail during execution, since watchSettled using Promise.allSettled under the hood, expectedValues would contain all the values of the settled asyncParams and errors would contain all errors if any.

Example

import { Request, Response, Next } from "express";
import prisma from "prisma";
import Deasyncify from "deasyncify";

export const getUserItems = async (req: Request, res: Response, next: Next) => {
    const [userItems, userItemsFindError] = await Deasyncify.watchSettled([
        this.prisma.cars.findOne({where: { ownersId: req.user.id } }),
        this.prisma.phones.findOne({ where: { ownersId: req.user.id }}),
        this.prisma.pets.findOne({ where: { ownersId: req.user.id }})
        ]);

    if(userItemsFindError.length > 0) return next(userItemsFindError);

    res.json(userItems);
};
You might also like...

Browser asynchronous http requests

It's AJAX All over again. Includes support for xmlHttpRequest, JSONP, CORS, and CommonJS Promises A. It is also isomorphic allowing you to require('re

Dec 20, 2022

A table component for your Mantine data-rich applications, supporting asynchronous data loading, column sorting, custom cell data rendering, row context menus, dark theme, and more.

A table component for your Mantine data-rich applications, supporting asynchronous data loading, column sorting, custom cell data rendering, row context menus, dark theme, and more.

Mantine DataTable A "dark-theme aware" table component for your Mantine UI data-rich applications, featuring asynchronous data loading support, pagina

Jan 4, 2023

In this project I'll use Asynchronous Javascript to call an API and set the leaderboard of the best players.

Leaderboard Project In this project I'll use Asynchronous Javascript to call an API and set the leaderboard of the best players. The main goals of thi

Oct 17, 2022

Catalogist is the easy way to catalog and make your software and (micro)services visible to your organization in a lightweight and developer-friendly way.

Catalogist is the easy way to catalog and make your software and (micro)services visible to your organization in a lightweight and developer-friendly way.

catalogist 📚 📓 📒 📖 🔖 The easy way to catalog and make your software and (micro)services visible to your organization through an API You were a pe

Dec 13, 2022

🎨 Beautify your github profile with this amazing tool, creating the readme your way in a simple and fast way 🚀 The best profile readme generator you will find ⚡

🎨 Beautify your github profile with this amazing tool, creating the readme your way in a simple and fast way 🚀 The best profile readme generator you will find ⚡

Demo Profile Readme Generator The best profile readme generator you will find! About | Technologies | Requirements | Starting | Contributing đŸŽ¯ About

Jan 1, 2023

đŸĻĢ A simple way to implement event sourcing in TypeScript

✨ Better DevX for Event Sourcing in TypeScript Castore provides a unified interface for implementing Event Sourcing in TypeScript. Define your events

Nov 18, 2022

An idiomatic way to enforce values not to be null nor undefined, with first-class support for TypeScript

nullthrows An idiomatic way to enforce values not to be null or undefined, with first-class support for TypeScript. Very lightweight with no dependenc

Jul 23, 2022

🔒 The new way to do types in typescript.

Nominal The right way to do types in typescript. Installation npm install nominal-types yarn install nominal-types pnpm install nominal-types Usage

Dec 24, 2022

An easy way to create a TypeScript library without hassle.

ts-lib-template An easy way to create a TypeScript library without hassle. ts-lib-template is a template for creating a TypeScript library. It comes b

Sep 13, 2022
Owner
Joseph Tsegen
Tech enthusiast | Full Stack Developer | Software Engineer.
Joseph Tsegen
Leader Board is a simple project based on JavaScript programing language. The purpose of this project is to work with APIs and ASYNC & AWAIT methods. I have used vanilla JavaScript with web pack to implement this project

Leader Board - JavaScript Project Table of contents Overview The challenge Screenshot Links Project Setup commands My process Built with What I learne

Mahdi Rezaei 7 Oct 21, 2022
A jQuery plugin for doing client-side translations in javascript.

About jQuery-i18n is a jQuery plugin for doing client-side translations in javascript. It is based heavily on javascript i18n that almost doesn't suck

Dave Perrett 202 May 19, 2021
This repository serves as a starter kit for doing simple TDD exercise

This repository serves as a starter kit for doing simple TDD exercise

adylanrff 3 Feb 19, 2022
Chris Siku 13 Aug 22, 2022
Cindy Dorantes 12 Oct 18, 2022
Provides event handling and an HTMLElement mixin for Declarative Shadow DOM in Hotwire Turbo.

Turbo Shadow Provides event handling and an HTMLElement mixin for Declarative Shadow DOM support in Hotwire Turbo. Requires Turbo 7.2 or higher. Quick

Whitefusion 17 Sep 28, 2022
Zero dependencies, lightweight, and asynchronous https requests package.

This project is a Work in Progress and currently in development. The API is subject to change without warning. A small fetching package for super simp

Ray Arayilakath 11 Dec 8, 2022
Cypress commands are asynchronous. It's a common pattern to use a then callback to get the value of a cypress command

cypress-thenify Rationale Cypress commands are asynchronous. It's a common pattern to use a then callback to get the value of a cypress command. Howev

Mikhail Bolotov 15 Oct 2, 2022