promise-watch
TypeScript icon, indicating that this package has built-in type declarations

1.1.5 • Public • Published

promise-watch

Build Status Greenkeeper badge

This module watches promise objects which have been made, and tells whether all promises have been settled or not.

Note about terminology

A Promise is in one of these states:
・pending: initial state, neither fulfilled nor rejected.
・fulfilled: meaning that the operation completed successfully.
・rejected: meaning that the operation failed.
Note: A promise is said to be settled if it is either fulfilled or rejected, but not pending.
Promise - JavaScript | MDN

Installing

npm install promise-watch

Usage example

https://higuri.github.io/promise-watch/

Code snippet from example page

const {PromiseWatch} = require("promise-watch");
 
function log(textarea, msg) { ... }
async function start3SecTask() { ... }
 
// loader: loading icon
const loader = document.querySelector(...);
// textarea: status lines
const textarea = document.querySelector(...);
// button: start a task
const button = document.querySelector(...);
 
// create a watch instance
const watch = new PromiseWatch();
// subscribe 'added' event
watch.onAdded(() => {
  if (loader.classList.contains("hidden")) {
    loader.classList.remove("hidden");
  }
});
// subscribe 'allSettled' event
watch.onAllSettled(() => {
  loader.classList.add("hidden");
});
 
button.addEventListener("click", async() => {
  log(textarea, "Start a task...");
  // run an asynchronous task through watch.run()
  await watch.run(start3SecTask());
  log(textarea, "Task finished !!");
});

full version

class PromiseWatch

Constructor

Example:

const watch = new PromiseWatch();

run(_: Promise<any>): Promise<any>

Example:

watch.run(asyncFunctionFoo(...))
.then(() => {
  // lines to be executed after Foo() ...
});
await watch.run(someAsyncFunctionFoo(...));
// lines to be executed after Foo() ...
watch.run(someAsyncFunctionFoo(...));
// lines to be executed in asynchronously with Foo() ...

onAdded(_: (Promise<any>) => void): void

Example:

watch.onAdded(() => {
  console.log("There are one or more pending tasks!");
});

onAllSettled(_: () => void): void

Example:

watch.onAllSettled(() => {
  console.log("There are no pending tasks!");
});

onOneSettled(_: (Promise<any>) => void): void

Example:

watch.onOneSettled(() => {
  console.log("A promise is fulfilled or rejected!");
});

pendings: Array<Promise<any>>

Example:

console.log(`Number of pending tasks: ${watch.pendings.length}`);

License

MIT license

Readme

Keywords

Package Sidebar

Install

npm i promise-watch

Weekly Downloads

9

Version

1.1.5

License

MIT

Unpacked Size

10.1 kB

Total Files

13

Last publish

Collaborators

  • higuri