1.0.0 • Published 5 years ago

sync-looper v1.0.0

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

sync-looper

This is useful when you want to sample an asynchronious response until it completes. For example, you want to test a module that asynchroniously writes logs. In your test you are expecting to find a specific log entry.

How does it Work

You need to wrap your sampling function with an iterator. This iterator returns 3 states, each leads to a different outcome:

  • when the iterator returns data the loop stops and returns that data
  • when the iterator returns an error the loop stops and returns that error
  • when the iterator returns neither data nor error the loop continues

When the loop reaches maximum repetitions it ends with an error.

Install

$ npm install --save sync-looper

Usage

This module has two classes:

  • The Callback Looper that works with first-error callback functions.
  • The Async Looper that works with async functions

Callback Looper Example:

const { CallbackLooper } = require("sync-looper");
const callbackLooper = new CallbackLooper();
	
let response = null;

// mock an async task that takes 3000 milliseconds
setTimeout(() => {
    response = "data";
}, 3000);

callbackLooper.constWait(
    (repetition, next) => {
        console.info(`repetition ${repetition} for longFunction`);

        if (response == null) return next(); // The response completed and contains the data I expected
        else if (response == "data") return next(null, response); // The response did not complete yet
        else return next("error"); // The response completed with an error
    },
    1000, // wait 1000 milliseconds before repeat
    4, // no more than 4 repetitions
    (err, data) => {
        if (err) console.error(err); // The loop ended with error
        else console.log(data); // The loop ended with the expected data
    }
);

Async Looper Example:

const { AsyncLooper } = require("sync-looper");
const asyncLooper = new AsyncLooper();

let response;

// mock an async task that takes 3000 milliseconds
setTimeout(() => {
    response = "data";
}, 3000);

const run = async () => {
    try {
        const data = await asyncLooper.constWait(
            async repetition => {
                console.info(`repetition ${repetition} for longFunction`);

                if (response == null) return null; // The response completed and contains the data I expected
                else if (response == "data") return response; // The response did not complete yet
                else throw new Error("error"); // The response completed with an error
            },
            1000, // wait 1000 milliseconds before repeat
            4 // no more than 4 repetitions
        );

        console.log(data); // The loop ended with the expected data
    }
    catch (err) {
        console.error(err); // The loop ended with error
    }
}

run();