• Stars
    star
    399
  • Rank 108,092 (Top 3 %)
  • Language
    JavaScript
  • Created almost 15 years ago
  • Updated about 4 years ago

Reviews

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

Repository Details

Promise utilities for Node

This package is deprecated, as the Node now provides this functionality itself. This package exists only for historical purposes.

The node-promise project provides a complete promise implementation. Promises provide a clean separation of concerns between asynchronous behavior and the interface so asynchronous functions can be called without callbacks, and callback interaction can be done on the generic promise interface. The node-promise package provides just a promise implementation, however, https://github.com/kriszyp/promised-io is recommended for more complete promise-based IO functionality. The promised-io includes the promise implementation from node-promise, as well as wrappers around Node's filesystem and other system I/O APIs for consistent promise-based interaction.

The node-promise module features a promise implementation with:

  • Chainable promises
  • Promises throw errors if an error handler is not provided
  • CommonJS promise proposal [1] compliant
  • Immutable once fulfilled to reduce possible side-effects
  • Promises can be used securely (as separate resolver/promise pairs in ocap situations)
  • Backwards compatibility where possible (addCallback, addErrback, emitSuccess, and emitError should still behave as expected)

Utility functions, including:

  • when() - Normalization of sync (normal values) and async (promises)
  • all() - Create a promise that accumulate multiple concurrent promises (failed promises resolve to Error objects)
  • allOrNone() - Ditto, but the first promise to fail causes the composition to fail as well
  • first() - Find the first promise to be fulfilled in a group of promises
  • seq() - Sequentially execute a set of promise returning functions
  • delay() - Returns a promise that is fulfilled after a given amount of time
  • execute() - Executes a function that takes a callback and returns a promise (thank you Benjamin Thomas for providing this)

Much of this is adapted from Tyler Close's ref_send and Kris Kowal's work on promises.

Some quick examples from test-promise.js (again, it is recommended that you use http://github.com/kriszyp/promised-io for file and other I/O interaction): util = require('util'); var fs = require('./fs-promise');

// open a file and read it
fs.open("fs-promise.js", process.O_RDONLY).then(function(fd){
  return fs.read(fd, 4096);
}).then(function(args){
  util.puts(args[0]); // print the contents of the file
});

// does the same thing
fs.readFile("fs-promise.js").addCallback(util.puts);

A default Promise constructor can be used to create a self-resolving deferred/promise:

var Promise = require("promise").Promise;
var promise = new Promise();
asyncOperation(function(){
  Promise.resolve("successful result");
});
promise -> given to the consumer

A consumer can use the promise:

promise.then(function(result){
   ... when the action is complete this is executed ...
},
function(error){
    ... executed when the promise fails
});

Alternately, a provider can create a deferred and resolve it when it completes an action. The deferred object a promise object that provides a separation of consumer and producer to protect promises from being fulfilled by untrusted code.

var defer = require("promise").defer;
var deferred = defer();
asyncOperation(function(){
  deferred.resolve("succesful result");
});
deferred.promise -> given to the consumer

Another way that a consumer can use promises:

var when = require("promise").when;
when(promise,function(result){
   ... when the action is complete this is executed ...
},
function(error){
   ... executed when the promise fails
});

More examples:

function printFirstAndList(itemsDeferred){
  findFirst(itemsDeferred).then(util.puts);
  findLast(itemsDeferred).then(util.puts);
}
function findFirst(itemsDeferred){
  return itemsDeferred.then(function(items){
    return items[0];
  });
}
function findLast(itemsDeferred){
  return itemsDeferred.then(function(items){
    return items[items.length];
  });
}

And now you can do:

printFirstAndLast(someAsyncFunction());

The workhorse function of this library is the "when" function, which provides a means for normalizing interaction with values and functions that may be a normal synchronous value, or may be a promise (asynchronously fulfilled). The when() function takes a value that may be a promise or a normal value for the first function, and when the value is ready executes the function provided as the second argument (immediately in the case of a non-promise normal value). The value returned from when() is the result of the execution of the provided function, and returns a promise if provided a promise or synchronously returns a normal value if provided a non-promise value. This makes it easy to "chain" computations together. This allows us to write code that is agnostic to sync/async interfaces:

var when = require("promise").when;
function printFirstAndLast(items){
  // print the first and last item
  when(findFirst(items), util.puts);
  when(findLast(items), util.puts);
}
function findFirst(items){
   // return the first item
   return when(items, function(items){
     return items[0];
   });
}
function findLast(items){
   // return the last item
   return when(items, function(items){
     return items[items.length - 1];
   });
}

Now we can do:

> printFirstAndLast([1,2,3,4,5]);
1
5

And we can also provide asynchronous promise:

var promise = new process.Promise();
> printFirstAndLast(promise);

(nothing printed yet)

> promise.emitSuccess([2,4,6,8,10]);
2
10

The "all" function is intended to provide a means for waiting for the completion of an array of promises. The "all" function should be passed an array of promises, and it returns an promise that is fulfilled once all the promises in the array are fulfilled. The returned promise's resolved value will be an array with the resolved values of all of the promises in the passed in array.

The "first" function is intended to provide a means for waiting for the completion of the first promise in an array of promises to be fulfilled. The "first" function should be passed an array of promises, and it returns an promise that is fulfilled once the first promise in the array is fulfilled. The returned promise's resolved value will be the resolved value of the first fulfilled promise.

More Repositories

1

json-schema

JSON Schema specifications, reference schemas, and a CommonJS implementation
JavaScript
505
star
2

multi-node

Multi-node provides launching of multiple NodeJS processes for TCP/HTTP serving
JavaScript
491
star
3

lmdb-js

Simple, efficient, ultra-fast, scalable data store wrapper for LMDB
JavaScript
358
star
4

msgpackr

Ultra-fast MessagePack implementation with extension for record and structural cloning / msgpack.org[JavaScript/NodeJS]
JavaScript
339
star
5

put-selector

A high-performance, lightweight function for creating and manipulating DOM elements with succinct, elegant, familiar CSS selector-based syntax
JavaScript
290
star
6

promised-io

Promise-based IO for JavaScript.
JavaScript
237
star
7

nodules

Asynchronous URL-based CommonJS module loader for Node with automated dependency resolution and module reloading
JavaScript
198
star
8

cbor-x

Ultra-fast CBOR encoder/decoder with extensions for records and structural cloning
JavaScript
176
star
9

alkali

Alkali is library for functional reactive data flows that drive native-based UI elements
JavaScript
162
star
10

compose

ComposeJS is a lightweight JavaScript library for object composition
JavaScript
127
star
11

xstyle

A declarative, reactive framework that extends CSS
JavaScript
98
star
12

cpm

CommonJS Package Manager
JavaScript
95
star
13

commonjs-utils

Utility modules for CommonJS
JavaScript
89
star
14

transporter

Transporter is JSGI application that serves modules to the browser with dependencies included and packaged in the CommonJS module transport format.
JavaScript
40
star
15

dbind

Data bindings for Dojo
JavaScript
29
star
16

weak-lru-cache

A cache using LRU and weak references to cache data in a way that works in harmony with garbage collection
JavaScript
28
star
17

persevere

The Persevere server features a secure RESTful JSON interface for data interaction and storage of dynamic data, JSONQuery/JSONPath querying, Comet-based real-time data notification through Rest Channels and Bayeux support, class-based based object-oriented business logic with data integrity and validation through JSON Schema in its server-side JavaScript environment.
JavaScript
21
star
18

patr

Promise-based asynchronous test runner for JavaScript
JavaScript
16
star
19

lmdbx-js

Wrapper for libmdbx
C++
15
star
20

ua-optimized

AMD plugin for UA-based optimization of feature-detection-has.js based modules
JavaScript
13
star
21

alkali-todo

TodoMVC written with Alkali
JavaScript
12
star
22

each

Multi-purpose iteration function
JavaScript
9
star
23

eslint-plugin-auto-import

ESLint plugin for automatically importing modules
JavaScript
9
star
24

commonjs-package-template

A template for packages in the Dojo foundation package repository
JavaScript
8
star
25

cpr

CommonJS Package Repository with Git integration
JavaScript
7
star
26

bindr

Bindr is a declarative functional reactive binding language
JavaScript
7
star
27

cobase

Composable data stores from reactive JavaScript Join, Transform, Index, and Reduce functions, built on Alkali & LevelDB
TypeScript
7
star
28

babel-plugin-transform-safely

A Babel plugin for transforming expressions with safe property access and modifications, checking parent existence
JavaScript
7
star
29

litmus

An viewer/editor for exploring Alkali variable data flow/dependencies, and their connection to visual DOM elements on a page
JavaScript
7
star
30

cbor-records

Registration for CBOR tag for records
6
star
31

json-tools

CommonJS tools for interaction with JSON and JSON-style structured data
JavaScript
5
star
32

ordered-binary

Representation of JavaScript primitives as a Buffer such that binary order matches natural order of primitives
JavaScript
5
star
33

caesium

Caesium is a collection of CSS tools, including an AMD CSS loader and builder.
JavaScript
4
star
34

node-commonjs

Modules implementing CommonJS specifications on top of Node
JavaScript
4
star
35

babel-plugin-transform-alkali

Babel plugin to transform reactive expressions using alkali.
JavaScript
3
star
36

splinterdb-js

Initial exploration of JS library for SplinterDB
JavaScript
3
star
37

msgpackr-extract

Node addon for string extraction for msgpackr
C++
3
star
38

jss

JSON Stylesheets
JavaScript
2
star
39

coffeetoes6

A very simple coffeescript to ES6 converter with minimal code modification without extra syntactic requirements (you will need to make fixes afterwards)
JavaScript
2
star
40

window-name

Cross-domain browser communication using the window.name transport
JavaScript
2
star
41

literally-typed

A literate form of TypeScript for embedding type information in documentation
JavaScript
2
star
42

xstyle-todo

TodoMVC on xstyle (and dstore)
JavaScript
2
star
43

cbor-extract

C++
2
star
44

persvr-org

Code/contents of persvr.org
JavaScript
1
star
45

backtrace-c

Print C/C++ level backtraces in NodeJS
1
star
46

mysql-store

A MySQL object store implementation for NodeJS
1
star
47

ddoc

dgrid based documentation
JavaScript
1
star
48

db-benchmark

JavaScript
1
star
49

presly

Why am I using Keynote and Powerpoint when I could use dojo.gfx?
JavaScript
1
star