1.0.3 • Published 4 months ago

@bugtamer/async-status v1.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

AsyncStatus JS

Manages the status of an async process.

Table Of Content

Installation

As project dependency

npm i @bugtamer/async-status

Available at npmjs.com

As script dependency

'require' demo example

const bugtamer = require("@bugtamer/async-status")
const dataAsyncStatus = new bugtamer.AsyncStatus();

or

const bugtamer = require("@bugtamer/async-status/lib/async-status")
const dataAsyncStatus = new bugtamer.AsyncStatus();

'import' demo example

import { AsyncStatus } from '@bugtamer/async-status/lib/async-status';
const dataAsyncStatus = new AsyncStatus();

Basic usage snippets

async / await

dataAsyncStatus.start();
try {
    data = await fetchData();
    dataAsyncStatus.end();
} catch (error) {
    dataAsyncStatus.abort();
}

Observable

dataAsyncStatus.start();
const subscription = fetchData().subscribe(
    response => {
        data = response;
        dataAsyncStatus.end();
    },
    error => {
        dataAsyncStatus.abort();
    }
);

Status management / Class interface

Use

Current StateMethod called / SentenceOutcome
new AsyncStatus()idle state
idlestart()ongoing state
ongoingend()idle state
ongoingabort()idle state
ongoingstart()Throw an error
idleend()Throw an error
idleabort()Throw an error

Do not try to manage these errors, just fix your code. They point out that some method should never have called.

Check attempt stats

SentenceDescription
dataAsyncStatus.attemptsreturns the number of calls to start()
dataAsyncStatus.successfulAttemptsreturns the number of calls to end()
dataAsyncStatus.failedAttemptsreturns the number of calls to abort()
dataAsyncStatus.resetAttemptStats()all previous counters are set to 0

Check current state

In this section we understand by call a call to any of the following methods: start(), end() or abort().

Idle State

There is no process activity.

dataAsyncStatus.isIdleReturns
When start() was never executed or the last call was end() or abort()true
In any other casefalse

Ongoing state

There is a process in progress.

dataAsyncStatus.isOngoingReturns
When the last call was start() and therefore neither end() nor abort() have been called yettrue
In any other casefalse

Check last outcome state

In this section we understand by call a call to any of the following methods: start(), end() or abort().

A successful outcome

dataAsyncStatus.wasSuccessfulReturns
When end() was the last method calledtrue
In any other casefalse

A failed outcome

dataAsyncStatus.wasFailedReturns
When abort() was the last method calledtrue
In any other casefalse

Measure the time

In milliseconds (ms):

dataAsyncStatus.elapsedTimeReturns
when start() was never calledAsyncStatus.UNDEFINED_TIME (-1)
when start() was called but end() or abort() has not yet been calledTime elapsed since the call to start() to current time
when start() was called and eventually end() or abort() was also calledElapsed time from call to start() to end() or abort() call

Final notes

  • Using a single instance of AsyncStatus to control multiple independent asynchronous processes that overlap in time could lead to erratic behavior in your program.

  • start() throws an error when is called more than Number.MAX_SAFE_INTEGER times (although is nearly unreachable).

Examples

// const bugtamer = require("@bugtamer/async-status/lib/async-status")
const bugtamer = require("@bugtamer/async-status")


function showStats(asyncStatus, message) {
    console.log(message)
    console.log(`  - Attempts:     ${asyncStatus.attempts}`)
    console.log(`    - successful: ${asyncStatus.successfulAttempts}`)
    console.log(`    - failed:     ${asyncStatus.failedAttempts}`)
    console.log(`  - State:`)
    console.log(`    - idle:       ${asyncStatus.isIdle}`)
    console.log(`    - ongoing:    ${asyncStatus.isOngoing}`)
    console.log(`  - Outcome:`)
    console.log(`    - successful: ${asyncStatus.wasSuccessful}`)
    console.log(`    - failed:     ${asyncStatus.wasFailed}`)
    console.log(`  - Time elapsed: ${asyncStatus.elapsedTime} ms`)
}


// Let's show where the Internation Space Station currently is.
console.log("Let's see where the ISS is with Node " + process.version);

// We can use any package from NPM since they are all built in.
var getJSON = require("async-get-json"); 


const status = new bugtamer.AsyncStatus();
showStats(status, 'new AsyncStatus()')

status.start()
showStats(status, 'start()')


const url = "http://api.open-notify.org/iss-now.json"; // change it to make it fail
try {
    // And we can use ES7 async/await to pull the ISS's position from the open API.
    var result = await getJSON(url);

    status.end()
    showStats(status, 'end()')
} catch (error) {
    status.abort()
    showStats(status, 'abort()')
}


if (!!result) {
    // RunKit will automatically display the last statement and try to find its best representation:
    result.iss_position;
}

Example output

Let's see where the ISS is with Node v14.20.1
new AsyncStatus()
  - Attempts:     0
    - successful: 0
    - failed:     0
  - State:
    - idle:       true
    - ongoing:    false
  - Outcome:
    - successful: false
    - failed:     false
  - Time elapsed: -1 ms
start()
  - Attempts:     1
    - successful: 0
    - failed:     0
  - State:
    - idle:       false
    - ongoing:    true
  - Outcome:
    - successful: false
    - failed:     false
  - Time elapsed: 1 ms
end()
  - Attempts:     1
    - successful: 1
    - failed:     0
  - State:
    - idle:       true
    - ongoing:    false
  - Outcome:
    - successful: true
    - failed:     false
  - Time elapsed: 75 ms