promise-lib
TypeScript icon, indicating that this package has built-in type declarations

0.1.4 • Public • Published

PLib

Usage

Plib is a Promise Utility Library. This is meant to make it useful when you need to work with lots of async functions or are performing async operations in loops.

import {PArray,CallBack} from "promise-lib";

PArray

PLib allows async operations to happen over an array. Standard Array methods can be used with async versions.

eg.

    import {PArray} from "promise-lib";

    let files = ["file.txt","file2.txt"];

    files = new PArray(files);

    let file_content = files.map(async function(file){

        return new Promise(function(resolve,reject){
            fs.readFile(file,"utf8",function(err,content){
                if(err){
                    return reject(err)
                }else{
                    resolve(content);
                }
            });
        })
    })

This can be quite ugly to look at however so using the callback utility we can rewrite the following.

    import {PArray,CallBack} from "promise-lib";

    let files = ["file.txt","file2.txt"];

    files = new PArray(files);

    let file_content = files.map(async function(file){
        let [err,content]  =  await CallBack.Call(fs.readFile,file,"utf8")
        if(err) throw err;
        return content;
    })

This helps code remain clean and declarative.

CallBack

CallBack which has been used in the example above can be used as a quick way to take a callback accepting function and make it a promise call. This will help to promote cleaner code.

A standard CallBack that can be converted to make things easier is any IO operation that takes a callback as it's last parameter.

     //...
     let [err,content]  =  await CallBack.Call(fs.readFile,file,"utf8")
     console.log(content);
     //continue working with content
     
     //Compared
     fs.readFile(file,"utf8",function(err,content){
         //Callback Hell
         console.log(content);
         //continue working with content
     })

Package Sidebar

Install

npm i promise-lib

Weekly Downloads

3

Version

0.1.4

License

ISC

Last publish

Collaborators

  • shavyg2