项目作者: gruhn

项目描述 :
Don't callback, callforth! :running:
高级语言: JavaScript
项目地址: git://github.com/gruhn/callforth.git
创建时间: 2019-08-23T18:35:23Z
项目社区:https://github.com/gruhn/callforth

开源协议:

下载


Callforth :running:

npm version
minzipped size

A tiny utility library to replace callbacks with Promises where possible.
Don’t callback, callforth!

It simply includes a hand-full of functions I see myself re-implementing in nearly every project.
So I might as well put them in a package.

Do things like:

  1. await timeout(3000)
  1. await eventOn(videoElement, "loadeddata")
  1. const message = await eventOn(webWorker, "message")

Install :package:

  1. npm install callforth

Now you can:

  1. import { eventOn, timeout, polling } from "callforth"

Alternatively, include this script and:

  1. <script src="./path/to/callforth.umd.js"></script>
  2. <script>
  3. const { eventOn, timeout, polling } = window.callforth
  4. </script>

API :eyes:

eventOn

  1. const payload = await eventOn(target, successEvent, errorEvent)

Parameters

  • target : EventTarget - any object you can call addEventListener on.
  • successEvent : string - name of the event you want to await.
  • errorEvent : string (optional) - if this event fires, the promise is rejected.

Return Value

  • Promise<any> - wraps callback result (callbacks first argument)

timeout

  1. await timeout(delay)

Parameters

  • delay : int - milliseconds after which the Promise should resolves.

Return Value

  • Promise<void>

polling

  1. await polling(predicate, { maxTries, interval })

Parameters

  • predicate : any -> boolean - delay in milliseconds after which the Promise should resolve.
  • options : object (optional)
    • maxTries : int (default = 10) - maximum number of times to call predicate before giving up.
    • interval : int (default = 10) - delay in milliseconds between calls of predicate.

Return Value

  • Promise<void>

More Examples

  1. async function loadScript(url) {
  2. let script = document.createElement("script")
  3. script.src = url
  4. await eventOn(script, "loaded")
  5. }
  1. async function primesLessThen(number) {
  2. primeWorker.postMessage(number)
  3. const result = await eventOn(primeWorker, "message")
  4. return result
  5. }