context-block

1.0.20 • Public • Published

context-block

Contextualized promise blocks by name and symbol. Supports async, promises, generators, and manual reject/resolve.



What/Why?

context-block is intended to assist in managing promises and asynchronous behaviors.

Imagine you want to update a UI based on the result of a service request - or multiple service requests without blocking user input. Maybe you are writing server logic and you want to ensure that you avoid sending multiple of database lookups simultaneously.

Context-block provides a developer friendly syntax that will ensure multiple of the same asynchronous activities are not occurring.



Install

npm install --save-dev context-block


API Reference


  • # Block

    Blocks are segments of code associated with a name. Blocks can either be Forward or Reverse. Forward blocks ALWAYS execute the latest code segment. Reverse blocks only execute the latest code segment if one is not already scheduled to run.


    Blocks return Contexts or ReverseContexts (which extend Promise) and associate the behavior of an asynchronous action with a name. A name can be either string or symbol, allowing asynchronous behaviors to be managed at various hierarchies (component vs global levels). Blocks also support a tagged literal format to help differentiate Blocks from other code (example)


    There are three forward and reverse block behavior functions defined.

    • block.dismiss(name[,fn,delay])
      Returns a Context for name and executes fn. If another block of the same name is created, the returned Context will be dismissed (rejected).

    • block.stop(name[,fn,delay])
      Returns a Context for name and executes fn. If another block of the same name is created, the returned Context will NOT be resolved or rejected.

    • block.join(name[,fn,delay])
      Returns a Context for name and executes fn. If another block of the same name is created, the returned Context will resolve/reject with the result of the new block.

    • block.reverse.dismiss(name[,fn,delay])
      Returns a ReverseContext for name and only executes fn if another block of the same name is not already scheduled to activate. If another block already exists, the returned ReverseContext will be automatically dismissed.

    • block.reverse.stop(name[,fn,delay])
      Returns a ReverseContext for name and only executes fn if another block of the same name is not already scheduled to activate. If another block already exists, the returned ReverseContext will not resolve or reject

    • block.reverse.join(name[,fn,delay])
      Returns a ReverseContext for name and only executes fn if another block of the same name is not already scheduled to activate. If another block already exists, the returned ReverseContext will resolve or reject with the result of the existing block. Additionally, if a block of the same name is created, the returned ReverseContext will resolve/reject with the result of the new block

    Blocks accept the following arguments:

name
requiredNames are symbols or strings used to bind a single function that resolves or rejects associated contexts. Contexts define their behavior when a naming collision occurs. After a context resolves, rejects, or stops, the name will become free again.
fn
optionalfunction that will be called. "fn" can either be a promise (example), a function with ({reject,resolve}) arguments (example), return a promise (example), async/await (example), or a generator (example). A Forward Block will always call "fn". Reverse blocks only call "fn" if the name is not already in use.
delay
optionaltime(ms) to wait before invoking "fn"




  • # Context extends Promise

    Contexts are the returned value from a Block and are not intended to be constructed directly. Contexts extend from promises and integrate Promise functionality such as Promise.all, Promise.race (example) and much more!

    The premise behind Contexts are that multiple contexts can potentially exist for a given Block name. However, each context decides how to act in the event multiple Contexts of the same name are created. Context actions include:

    • dismiss
      Rejects if another Context of the same name is created

    • stop
      Does not resolve or reject if another Context of the same name is created

    • join Resolves or rejects with the latest result




  • # ReverseContext extends Context

    ReverseContexts take Contexts a step further by deciding the action if a Block already exists.

    ReverseContexts work under the premise that priority lies with an earlier Context, which naturally changes the meaning of dismiss, stop, and join:

    • dismiss
      Rejects if another Context of the same name is already active

    • stop
      Does not resolve or reject if another Context of the same name is already active

    • join
      Resolves or rejects with the result of an already active Context. Additionally can resolve or reject with a later Context's result.




Examples

Tagged Literal

const block = require('context-block');

//tagged literal block with unspecified dismiss,stop,join defaults to dismiss.
block `test` (({reject,resolve})=>{
    //never called
}).then(()=>{
    //never called
}).catch((v)=>{
    console.error(v); // "dismissed"
});

//tagged literal block with specified method
//context will be dismissed as another context will activate with the same name
block.dismiss `test` (()=>{
    return new Promise((resolve,reject)=>{
        resolve('hello world');
    });
}).catch ((v)=>{
    console.error(v); //v is "dismissed"
}); 

//untagged equivalents for reference
//another context of the same is defined again, so nothing nothing will get called
block.stop('test',({reject,resolve})=> {
    //never called
}).catch((v)=>{
    	//never called
});

//join context will result in "world" because the last context resolves "world"
block('test').join(({reject,resolve})=>{
    resolve('hello');
}).then((v)=>{
    	console.error(v); //v is "world"
});

block.join `test` (({reject,resolve})=>{
    resolve('world');
}).then((v)=>{
    	console.error(v); //v is "world"
});

OUTPUT:
dismissed
dismissed
world
world

fn is a promise

block.dismiss `test` (new Promise((resolve,reject)=>{
    resolve('hi');
})).then((v)=>{
    console.error(v); //v is "hi"
});


OUTPUT:
hi

fn synchronously references resolve/reject arguments

//note the es6 destructure syntax
//if you specify resolve, reject arguments, you must resolve the context using them!!!
block `test` (({resolve,reject})=>{
    resolve(1);
}).then((v)=>{
    console.error(v); //v is 1
});

OUTPUT:
1

fn returns a promise

block `test` (()=>{
    return new Promise((resolve,reject)=>{
        resolve(2);
    });
}).then((v)=>{
    console.error(v); //v is 2
});

OUTPUT:
1

fn uses async/await

async function getSomething () {
    return new Promise((resolve,reject)=>{
        resolve('banana');
    });
}
block `test` (async ()=>{
    return await getSomething('for my monkey');
}).then((v)=>{
    console.error(v); //v is "banana"
});

OUTPUT:
banana

fn is a generator (behaves as a coroutine)

block `test` (function * () {
    yield new Promise((resolve,reject)=>{
        setTimeout(()=>resolve(1),20)
    });
    yield 2;
    yield new Promise((resolve,reject)=>{
        resolve(3);
    });
    return 4
}).then((v)=>{
    console.error(v); //v is [1,2,3,4]
});

OUTPUT:
1,2,3,4

Contexts integrate with promise functionalities (Promise.all & Promise.race)

Promise.all([
    block `test1` (({resolve,reject})=>{resolve(1);}),
    block `test2` (({resolve,reject})=>{resolve(2);})
]).then((v)=>{
    console.log(v);
});


OUTPUT:
1,2

------------

Promise.race([
    block `test1` (({resolve,reject})=>{resolve(1);}),
    block `test2` (({resolve,reject})=>{setTimeout(()=>resolve(2));})
]).then((v)=>{
    console.log(v);
});


OUTPUT:
1

Package Sidebar

Install

npm i context-block

Weekly Downloads

3

Version

1.0.20

License

ISC

Last publish

Collaborators

  • tadaa