1.0.0 • Published 5 years ago

@oprasad/callback v1.0.0

Weekly downloads
1
License
ISC
Repository
-
Last release
5 years ago

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 support@oprasadhelp.freshdesk.com

1.0.0

5 years ago