• Stars
    star
    149
  • Rank 248,619 (Top 5 %)
  • Language
    TypeScript
  • License
    Other
  • Created over 9 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Async coordination primitives and extensions on top of ES6 Promises

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.

More Repositories

1

reflect-metadata

Prototype for a Metadata Reflection API for ECMAScript
TypeScript
2,999
star
2

proposal-enum

Proposal for ECMAScript enums
HTML
214
star
3

grammarkdown

Markdown-like DSL for defining grammatical syntax for programming languages.
HTML
118
star
4

iterable-query

Query API over JavaScript (ECMAScript) Iterators
TypeScript
66
star
5

proposal-shorthand-improvements

A proposal to introduce new shorthand assignment forms for ECMAScript object literals
HTML
64
star
6

obs-remote

A touch-friendly desktop application designed for tablets that can be used to control OBS Studio remotely using 'obs-websocket'
TypeScript
36
star
7

proposal-functional-operators

Proposal for the additon of functional operators to ECMAScript
HTML
23
star
8

proposal-regexp-features

Proposal to investigate additional language features for ECMAScript Regular Expressions
JavaScript
19
star
9

asyncjs

Asynchronous coordination primatives for TypeScript and JavaScript
JavaScript
13
star
10

proposal-statements-as-expressions

Proposal to explore Statements as Expressions
JavaScript
12
star
11

proposal-struct

Value Types (i.e., 'struct') for ECMAScript
JavaScript
12
star
12

regexp-features

A comparison of Regular Expression features in various languages and libraries.
JavaScript
9
star
13

tsserver-live-reload

VSCode Extension to automatically restart the TypeScript Language Server when it changes.
TypeScript
8
star
14

graphmodel

JavaScript library for modeling directed graphs
TypeScript
7
star
15

sourcemap-visualizer

Source Map parser and visualizer
TypeScript
6
star
16

service-composition

Decorator-based dependency injection library.
TypeScript
5
star
17

iterable-query-linq

LINQ-like syntax via ECMAScript tagged templates
TypeScript
5
star
18

regexp-match-indices

Polyfill for the RegExp Match Indices proposal
TypeScript
4
star
19

posh-vsdev

Configures PowerShell to run as a Visual Studio Developer Command Prompt
PowerShell
4
star
20

promisejs

Promise/Future-based asynchrony in javascript
JavaScript
3
star
21

equatable

A low-level API for defining equality.
JavaScript
3
star
22

typedoc-plugin-linkrewriter

A TypeDoc plugin for rewriting links in markdown
TypeScript
2
star
23

chardata

Unicode character data
TypeScript
2
star
24

ecmarkup-vscode

ecmarkup language extensions for Visual Studio Code
HTML
2
star
25

fork-pipe

Fork/join stream processing.
TypeScript
2
star
26

chardata-generator

Generates TypeScript source files from the Unicode Character Database
TypeScript
1
star
27

typedoc-plugin-biblio

A TypeDoc plugin to support references to externally hosted documentation.
TypeScript
1
star
28

grammarkdown-server

Grammarkdown Language Server for VSCode
TypeScript
1
star
29

collection-core

Symbol-based augmentation API for interacting with collection-types in ECMAScript.
JavaScript
1
star
30

decorators

Annotations+Decorators TC39 proposal
HTML
1
star
31

rbuckton.github.io

1
star
32

grammarkdown-syntax

Grammarkdown Language Client for VSCode
JavaScript
1
star
33

proposal-regexp-conditionals

JavaScript
1
star
34

ecmascript-mirrors

Prototype and Proposal for a Mirrors API for ECMAScript, for use in tandem with Decorators.
TypeScript
1
star