npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@oprasad/callback

v1.0.0

Published

New callback to to handle multiple callbacks

Downloads

3

Readme

Introduction

This will help to track multiple results through callback and return consolidated result after all of them were received. This will take care of waiting and tracking, so that we can concentrate on business logic

Getting Started

Context

Lets assume that we are developping a travel portel that gets the travel options from 10 travel companies and provides a comparitive analysis. Once we have the user inputs, we need to initiate 10 web service calls. These calls will be typically asynchronous for performance reasons. Once we receive responses, we do the comparitive study and present the results

This will have following classes to help with the same CallbackHandler Class to manage multiple callbacks

Setup

Use standard NPM installation command to install @oprasad/callback from command prompt. Alternatively you can install oprasad, that will include this also

    npm install --save @oprasad/callback

CallbackHandler

The main class to manage multiple callbacks

API

CallbackHandler exposes following API for caller programs to call

handleSuccess(id : any, result : any)

Method to be invoked for success result. id will be unique identifier for source/call and result is the data

handleError(id : any, error : any)

Method to be invoked in case of error. id will be unique identifier for source/call and error is the error details

handleResult(id : any, error : any, result : any)

Common method can be invokes in case of success/error. If the error is 'undefined', it will be considered as success

Import

CallbackHandler has to be imported in the class that implements the user input for processing

    import {CallbackHandler} from 'oprasad/lib/callback/CallbackHandler'

Instantiate

Create the callback handler to wait for 10 results for 30 sec

    callbackHandler : CallbackHandler = new CallbackHandler(successHandler, errorHandler, noOfResults, timeout);

SuccessHandler

The function called if all success responses received with in the timeout period. In this case we will have travel options from all travel companies. Function performs comparitive study and present it to users

successHandler = function(results: Map<any, any>){
    //result will be map of the source and data
    //source is an identifier to uniquily identify the multiple callback results
    //data will be the information returned
    results.forEach((travelInfo, travelCompanyId, mapEntry) => {
        console.log('Received travel information ' + travelInfo + ' from ' + travelCompanyId);
        // any processing of the data received at individual level 
    });

    //process all options
    compareTrevelOptions(results.values());

    //further processing for user presenation
}

ErrorHandler

The function called if any error/no response received with in the timeout period. In this case we will have travel options from some of the travel companies and error from others. Based on business logic we can decide to present only received options/error

errorHandler = function(errors: Map<any, any>, results: Map<any, any>){
    //errors will be map of the source and the corresponding error received
    //Incase of timeout, there will be a single entry with key as 'Others' and error as 'Timeout' for all remaining entries
    //result will be similar to the one in successHandler, but only successfull execution
    errors.forEach((error, travelCompanyId, mapEntry) => {
        console.log('Received error ' + error + ' from ' + travelCompanyId);
        // any processing of the error received at individual level 
    });
    results.forEach((travelInfo, travelCompanyId, mapEntry) => {
        console.log('Received travel information ' + travelInfo + ' from ' + travelCompanyId);
        // any processing of the data received at individual level 
    });

    if(ignoreErrors){
        //process all options
        compareTrevelOptions(results.values());

        //further processing for user presenation
    } else {
        throw Error('Error while retrieving the information');
    }
}

noOfResults - Optional - Default 1

Number of call backs expected. The object will wait till time out period or 'noOfResults' of callbacks received

timeout(in milli sec) - Optional - Default 60,000 (1 min)

Number of milli seconds to wait before declaring timeout. 

Usage

There are different ways the callback handler can be associated with callers

as callback method

the 'handleResult' API can be passed as callback method, if the call supports the corresponding format. Please ensure to bind this while passing the method

var callbackHandler = new CallbackHandler(function(results : Map<any, any>){
    console.log('Task Completed Successfully.\n Result : ' + result)
    return;
}, function(errors : Map<any, any>, results ? : Map<any, any>){
    console.log('Task Failed. \n Errors : ' + errors)
    return;
});

let testCaller = function(callback : (id : any, error: any, result: any) => any ) {
    callback('<id>', undefined, '<result>');
}
testCaller(callbackHandler.handleResult.bind(callbackHandler));

as input parameter

The caller can invoke one of the above API to indicate success or error

var callbackHandler = new CallbackHandler(function(results : Map<any, any>){
    console.log('Task Completed Successfully.\n Result : ' + result)
    return;
}, function(errors : Map<any, any>, results ? : Map<any, any>){
    console.log('Task Failed. \n Errors : ' + errors)
    return;
});

let testCaller = function(callbackHandler : CallbackHandler ) {
    // in case of success
    callbackHandler.handleSuccess('<id>', '<result>');

    // in case of error
    callbackHandler.handleSuccess('<id>', '<error>');
}
testCaller(callbackHandler.handleResult.bind(callbackHandler));

as Observer

The callbackHandler can be registered as Observer for any observable object. Please refer to Observer package

`` var callbackHandler = new CallbackHandler(function(results : Map<any, any>){ console.log('Task Completed Successfully.\n Result : ' + result) return; }, function(errors : Map<any, any>, results ? : Map<any, any>){ console.log('Task Failed. \n Errors : ' + errors) return; });

let observable = new Observable();
observable.addObserver(observer);
observable.setProperty('source', 'result')

``

Support

If you have any issues/suggesitions/feedback, please send a mail to [email protected]