Code Monkey home page Code Monkey logo

prex's Introduction

Promise Extensions for JavaScript (prex)

Asynchronous coordination for JavaScript and TypeScript.

DEPRECATED: This package has been deprecated in favor of the following packages that replace it:]

This library contains a number of coordination primitives to assist in asynchronous application development in JavaScript and TypeScript. This includes useful additions for building complex asynchronous logic including:

Installing

For the latest version:

npm install prex

Documentation

Samples

Cancellation

API Reference: Cancellation

The CancellationTokenSource and CancellationToken primitives allow you to create asynchronous operations that can be canceled externally. The following is an example of a function used to download a file asynchronously that can be canceled:

import * as http from "http";
import * as fs from "fs";
import { CancellationTokenSource, CancellationToken } from "prex";

function downloadFile(from: string, to: string, token = CancellationToken.none) {
    return new Promise<void>((resolve, reject) => {
        const request = http.get(from);

        // abort the request if canceled.
        const registration = token.register(() => {
            request.abort();
            reject(new Error("Operation canceled."));
        });

        request.on("error", err => {
            registration.unregister();
            reject(err);
        });

        request.on("response", (response: http.IncomingMessage) => {
            response
                .pipe(fs.createWriteStream(to))
                .on("error", err => {
                    registration.unregister();
                    reject(err);
                })
                .on("end", () => {
                    registration.unregister();
                    resolve();
                });
        });
    });
}

async function main() {
    const source = new CancellationTokenSource();

    // cancel the source if the file takes more than one second to download
    setTimeout(() => source.cancel(), 1000);

    await downloadFile("http://tempuri.org/some/file", "file", source.token);
}

Coordination

API Reference: Coordination

A Semaphore can be used to protect access to a critical section of your code when you must limit access across multiple async operations. The following is an example of two functions which both need exclusive access to a single resource but could possibly be preempted when suspended while awaiting an asynchronous operation:

import { Semaphore } from "prex";

const criticalResource = new Semaphore(1);

async function updateCriticalLocalResource() {
    // Acquire a lock on the critical resource
    await criticalResource.wait();

    // Make local changes...

    // await a network resources
    await postUpdateToNetworkResource(changes);

    // release the lock
    criticalResource.release();
}

async function deleteCriticalLocalResource() {
    // Acquire a lock on the critical resource
    await criticalResource.wait();

    // Make local changes...

    // await a network resources
    await postUpdateToNetworkResource(changes);

    // release the lock
    criticalResource.release();
}

declare function postUpdateToNetworkResource(changes): Promise<void>;

A Barrier can be used to coordinate complex async operations:

import { Barrier } from "prex";

const barrier = new Barrier(/*participantCount*/ 3);

async function processNpcAI() {
    while (true) {
        // process AI activities...
        await barrier.signalAndWait();
    }
}

async function processGameRules() {
    while (true) {
        // process game rules
        await barrier.signalAndWait();
    }
}

async function processGameInput() {
    while (true) {
        // process user input
        await barrier.signalAndWait();
    }
}

Scheduling

API Reference: Scheduling

An AsyncQueue is a useful primitive for scheduling asynchronous work:

import { AsyncQueue } from "prex";

const workItems = new AsyncQueue();

function queueUserWorkItem(action: () => void) {
    workItems.put(action);
}

async function processWorkItems() {
    while (true) {
        const action = await workItems.get();
        try {
            action();
        }
        catch (e) {
            console.error(e);
        }
    }
}

License

Copyright (c) Microsoft Corporation. Licensed under the Apache License, Version 2.0.

See LICENSE file in the project root for details.

prex's People

Contributors

ikokostya avatar rbuckton avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prex's Issues

license

It is really nice work.
Have you considered changing to plain MIT license?

Does not work with IE 11

Im using the Semaphore feature in prex. It works great but in IE 11 I start getting syntax issues.

Tag new version

Hi there,
Please tag the new npm version (i.e. 0.4.7) of this module in this upstream repo.. we want to pack this awesome npm module to debian, so please do as soon as possible,

Regards,
VIVEK K J
www.vivekkj.me
Debian Community

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.