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

sync-promise-expanded

v1.0.0

Published

Ultra compact synchronized promise implementation.

Downloads

888

Readme

SyncPromise

A fast, small, safe promise implementation with synchronous promise resolution and an API which resembles ECMAScript promises.

SyncPromise is incompliant with the Promises/A+ spec, specifically part 2.2.4.

Why

Promises make handling asynchronous operations easier. IndexedDB exposes a lot of asynchronous operations. That sounds like a great match? Well, unfortunately things are not so simple It is not possible to use Promises/A+ promises inside IndexedDB transactions in a cross browser way.

SyncPromise was created because it's author wanted to use promises in IndexedDB transaction for the library SyncedDB – both internally and in the user facing API. It was released in the hope that it would be of use to others who work directly with IndexedDB.

Features

  • Weighs less than 1KB when minified (not gzipped).
  • Familiar API that is very similar to the native ECMAScript promises API.
  • Provides a safety mechanism to prevent releasing Zalgo
  • Distributed both as a CommonJS package, AMD module, global export and as a version suitable for including directly in other source code.

Safety

It is for good reason that the Promises/A+ specification requires asynchronous resolution! Without care taken one can end up creating promises that are sometimes synchronous and sometimes asynchronous. That is a very bad idea that leads to unpredictable non-deterministic behaviour (see this post for a detailed explanation).

Restrictions

Fortunately SyncPromise imposes two restrictions on usage. The first ensures that promises are never resolved immediately. The second makes sure that no errors get swallowed. Together these restrictions ensure that a promise chain will always be run asynchronously.

Promises that are synchronously resolved can't be chained

Throwing an exception directly in the promise body counts as a synchronous resolution and will therefore be resolved instead with setTimeout(..., 0).

new SyncPromise(function(resolve, reject) {
  resolve('foo'); // <- Will be treated as async resolve
}).then(function(result) {
  result === 'foo'; // true
});

new SyncPromise(function(resolve, reject) {
  setTimeout(resolve, 10); // <- Asynchronous resolve
}).then(function() {
  return 1; // Fine!
}).then(function(n) {
  n === 1; // true
});

Uncaught errors will be thrown if the rejection occurs within the SyncPromise function body and there is no catch, however:

new SyncPromise(function(res, rej) {
  setTimeout(function () {
    throw new Error('err');
  });
});

If a promise rejects, at least one onRejected callback must have been attached

This ensures that all rejected promises are handled. Other promise libraries (Bluebird for instance) use async mechanisms to ensure this.

const p = new SyncPromise(function(resolve, reject) {
  setTimeout(reject, 10); // Error is thrown – no rejection handlers attached yet
});
setTimeout(function() {
  p.catch(function() { });
}), 20;

Installation

Node.js/Browserify

npm install sync-promise-expanded

Then:

import SyncPromise from 'sync-promise-expanded';

SyncPromise.all([
  // ...
]);

Browser

npm install sync-promise-expanded

Then include the global export or the AMD module.

Example

// This is a wrapper around IDBStore#get.
// Had it been written using native promises it would have closed the
// transaction when calling `resolve` or `reject`
function getRecord(IDBStore, key) {
  return new SyncPromise(function(resolve, reject) {
    const req = IDBStore.get(key);
    req.onsuccess = function() {
      if (req.result !== undefined) {
        resolve(req.result);
      } else {
        reject('KeyNotFoundError');
      }
    };
    req.onerror = reject;
  });
}

// Usage
const tx = db.transaction('books', 'readonly');
const bookStore = tx.objectStore('books');

getRecord(bookStore, 'Bedrock Nights').then(function(book) {
  // We got the book, and the transaction is still open so we
  // can make another request. Had `getRecord` used native promises
  // the transaction whould have been closed by now.
});

Differences from ECMAScript promises

  • Synchronized resolution and rejection, of course.
  • Promise.resolve and Promise.reject are implemented with setTimeout(..., 0) as are resolve() and reject() when run synchronously.

API

new SyncPromise(function)

Creates a new promise. The passed function is passed callbacks to both resolve and reject the promise.

Example:

const p = new SyncPromise(function(resolve, reject) {
  const req = IDBStore.get(key);
  req.onsuccess = function() {
    if (req.result !== undefined) {
      resolve(req.result);
    } else {
      reject('KeyNotFoundError');
    }
  };
  req.onerror = reject;
});

SyncPromise#then(function)

The passed function will be called if the promise is fulfilled. A new promise chained from the original promise is returned. The new promise is resolved with the value that the function return. The new promise is rejected if the function throws an error.

Example:

getSomething.then(function(v) {
  return doSomething(v);
}).then(function(v) {
  doSomethingElse(v);
});

SyncPromise#catch(function)

The passed function will be called if the promise is rejected. A new promise chained from the original promise is returned. The new promise is resolved with the value that the function return. The new promise is rejected if the function throws an error.

Example:

getSomething.then(function(v) {
  return doSomething(v);
}).then(function(v) {
  doSomethingElse(v);
});

SyncPromise.all(array)

Return a promise that is resolved when all promises in the array has fulfilled. If one rejects, the promise is rejected for the same reason.

Example:

const ps = [
  new SyncPromise(function(resolve) {
    setTimeout(function() {
      resolve(1);
    }, 100);
  }),
  2,
  new SyncPromise(function(resolve) {
    setTimeout(function() {
      resolve(3);
    }, 9);
  }),
];
SyncPromise.all(ps).then(function(ns) {
  assert.deepEqual(ns, [1, 2, 3]);
});

SyncPromise.race(array)

Return a promise that is resolved when one of the promises in the array has fulfilled. If one rejects, the promise is rejected for the same reason.

Example:

const ps = [
  new SyncPromise(function(resolve) {
    resolve(1);
  }),
  2,
  new SyncPromise(function(resolve) {
    setTimeout(function() {
      resolve(3);
    }, 9);
  }),
];
SyncPromise.race(ps).then(function(ns) {
  assert.deepEqual(ns, 2);
});

SyncPromise.resolve(val)

Equivalent to:

return new SyncPromise(function(resolve, reject) {
  setTimeout(function () {
    resolve(val);
  }, 0);
});

SyncPromise.reject(val)

Equivalent to:

return new SyncPromise(function(resolve, reject) {
  setTimeout(function () {
    reject(val);
  }, 0);
});