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

chainjs

v0.2.1

Published

Flow controller for the complex function logic.

Downloads

26

Readme

chainjs

logo

Build Status Coverage Status Gitter npm version

An asynchronous callback's flow controller, chaining async function callbacks. Async methods calling flow make easy. I use it in node.js server and webapp.

Install

npm install chainjs --save

Usage

:two_men_holding_hands: :two_men_holding_hands: :two_men_holding_hands:

Chainjs can be used in node.js or browser . Use in node as below:

var Chain = require('chainjs')

Chain(function (chain, data) {
        // initialize
        console.log(data) // --> {name: 'Chainjs'}
        chain.next();
    })
    .then(function (chain) {
        chain.nextTo('branchStep')
    })
    .then(function (chain, data) {
        var count = chain.data('count' || 0)
        if (count > 2) {
            chain.next('thenStep')
        } else {
            setTimeout(function () {
                chain.data('count', count ++).retry()
            })
        }       
    })
    .branch('branchStep', function (chain) {
        chain.next('branchStep')
    })
    .then(function (chain, from) {
        if (from == 'branchStep') {
            // do something
        }
        chain.next()
    })
    .final(function (chain, data) {
       // do something when chain is ending
    })
    .start({name: 'Chainjs'})

:walking: :walking: :walking: :walking: :walking: :walking:

Look at the diagram of above chain-flow:

diagram

API

Each step's handler has been passed the chain instance as the first argument.

Chain(func, ..., funcN)

:running: API Reference

Create a Chain instance.

  • if arguments is not empty, it will be call .then() with arguments automatically.
  • else If first param is type of Array, then first param will be passed as arguments.
Chain(func /*, ..., funcN*/);
// or 
Chain([func, func1, funcN])

.then(func, ..., funcN)

:running: API Reference

Define a chain step, if a then step has multiple functions, it need each function call chain.next() to goto next step.

Chain().then(funcA1, funcA2, funcA3).then(func1)

If first argument is type of Array, that argument will be passed as arguments.

Chain.then([func, ..., funcN])
// equal to 
Chain.then(func, ..., funcN)

.retry()

:running: API Reference

Call current function once again (use for recursive).

var flag
Chain(function (chain, data) {
    if (flag) {
        return chain.next()
    }
    flag = true
    chain.retry()
}).start('value')

.some(func, ..., funcN)

:running: API Reference

Define a chain step, if a then step has multiple functions, it need any function of this step calling chain.next() only once to goto next step.

Chain(func).some(function (chain) {
    setTimeout(function () {
        chain.next()
    }, 100)
}, function (chain) {
    setTimeout(function () {
        chain.next()
    }, 1000)
}, function (chain) {
    setTimeout(function () {
        chain.next()
    }, 500)
}).then(function () {
    // this step will be run after 100ms.
})

If first argument is type of Array, that argument will be passed as arguments.

Chain.some([func1, func2, ..., funcN])
// equal to 
Chain.some(func1, func2, ..., funcN)

.each(func, ..., funcN)

:running: API Reference

Define a chain step, call each handlers of this step in sequence. In this step, each function call chain.next() to call next function. In orders from left to right of arguments

Chain(func).then(func1).each(funcA1, funcA2, funcA3)

If first argument is type of Array, that argument will be passed as arguments.

Chain.each([func1, func2, ..., funcN])
// equal to 
Chain.each(func1, func2, ..., funcN)

.start(data, ..., dataN)

:running: API Reference

Start running the chain, and could pass data to initial step.

Chain(function (chain, initData) {
    
}).then(func1).then(func2).start(initData);

.destroy()

:running: API Reference

Destroy the chain, mark the chain as ending and destroy local variable, but don't calling final funtions.

notice: after use chain.destroy(), the chain contiue execute current step handler, so use with return for stoping current step excution

Chain(func).then(function (chain) {
    chain.destroy();
    return;
}).start();

.next(data, ..., dataN)

:running: API Reference

Go to next step

chain.next();
// pass params to next step handler
chain.next(data);

.branch(branchName, func)

:running: API Reference

Define a branch step, only using chain.nextTo(branchName) to goto branch step. Call chain.next() from last step will skip next branch step.

     -------------o
     |            ↓
o----o----->o---->o---->o
Chain(function (chain) {
    chain.nextTo('branchA')
    chain.next()
}).then(function (chain) {
    throw new Error('This step should not be called')
}).branch('branchA', function (chain) {
    chain.next()
}).branch('branchB', function (chain) {
    throw new Error('This step should not be called')
}).final(function (chain) {
    // done
}).start()

.nextTo(branchName, data, ..., dataN)

:running: API Reference

Go to next branch.

Chain(function (chain) {
    chain.nextTo('branchA')
}).then(function (chain) {
    throw new Error('This step should not be called')
}).branch('branchA', function (chain) {
    chain.next()
})

Notice: .nextTo() should not goto previous step

Chain(function (chain) {
    chain.next()
}).branch('branchA', function (chain) {
    chain.next()
}).then(function (chain) {
    chain.nextTo('branchA') // will throw an error
}).start()

.wait(time, data, ..., dataN)

:running: API Reference

Waiting some time then call next step.Just a shortcut of setTimeout(function () {chain.next()}, time).

// pass params to next step handler
chain.wait(5000, data); // wait 5s then call next

.end(data, ..., dataN)

:running: API Reference

End up chain steps, mark the chain as ending, for cross steps data sharing

chain.end();
// pass params to final handler
chain.end(data);

.final(finalHandler)

:running: API Reference

Define a final step, witch will be invoke after call chain.end() or all step of this chain is over.

Chain(function (chain) {
    ...
    chain.end('ending initial step')

}).then(function (chain) {

    ...
    chain.next('step 2 calling')

}).final(function (chain, data) {
    console.log(data) // --> ending initial step
})

.data([key] [, value])

:running: API Reference

Saving data in current chain

// set data
chain.data('param', param);
// set multiple data in batch
chain.data({
    'param1': param1,
    'param2': param2,
    'param3': param3
});
// get data
chain.data('param');
// get all data
var chainData = chain.data();

.thunk(func)

:running: API Reference

Turn a regular node function into chainjs thunk.

 function handler1 (param, callback) {
    callback(param + 'Chain through step1, ')
}
function handler2 (param, callback) {
    callback(param + 'step2')
}
Chain()
    .then(Chain.thunk(handler1))
    .then(Chain.thunk(handler2))
    .final(function (chain, data) {
        console.log(data); // --> Initialize! Chain through step1, step2
    })
    .start('Initialize! ')

.context(ctx)

:running: API Reference

Binding "this" to specified ctx for all functions of each step of current chain.

Chain(function () {
    console.log(this); // --> "abc"
})
.then(function () {
    console.log(this); // --> "abc"
})
.context('abc')
.start()

Run Testing

npm test

Change Log

See change logs

License

The MIT License (MIT)

Copyright (c) 2013 guankaishe

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.