Skip to content

ThatsMrTalbot/async

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Async

Async utilities for typescript

This is a bunch or utils for working with async functions in typescript. All functions can be imported from the package or from their subpackage.

For example:

import or from '@thatsmrtalbot/async/or';
// Is equal to
import {or} from '@thatsmrtalbot/async';

This is usefull when the result is bundled for the web as it reduces unused code.

Utils

all

This is equivilent to Promise.all(). It follows the same syntax as the rest of these utils.

For example:

await all(
    () => repository.deleteUser(username),
    () => repository.deleteProfile(username),
    () => repository.deletePosts(username),
)

or

Or allows you to perform one or more actions until a non null value is returned.

For example:

let user = await or(
    () => repository.getUser(username),
    () => repository.createUser(username),
)

You can also use it to throw errors on null values:

let user = await or(
    () => repository.getUser(username),
    () => { throw new Error("User does not exist") },
)

promisify/promisifyAll

These are the similar to bluebird.promisify and bluebird.promisifyAll, without the additional promise implimentation.

let read = promisify(fs.read)
let fsAsync = promisifyAll(fs)
//read == fsAsync.readAsync

resolver

Resolver is a promise with external methods to resolve and reject.

let resolver = new Resolver<string>()
resolver.resolve("value")

tick

Tick uses setTimeout to defer the execution of a function for a tick.

await tick()

time

Time times the execution of a promise:

let user = await time(
    () => repository.getUser(uid),
    (err, time) => console.log(`Execution took ${time}`)
)

timeout

Timeout allows you to set a time limit for promises to resolve

await timeout(
    () => repository.getUser(uid),
    500,
)

wait

Tick uses setTimeout to wait a specified amount of time:

await wait(500)

array

Some async versions of array utils

let odd = await array([1,2,3,4,5]).filterAsync(async (value, index) => value % 2)
let even = await array([1,2,3,4,5]).mapAsync(async (value, index) => value * 2)
await array([1,2,3,4,5]).forEachAsync(async (value, index) => console.log(value))

dispatch

Dispatch promise values using keys

let dispatcher = new Dispatch();
let promise = dispatcher.next("key");

dispatcher.dispatch("key", "value");

console.log(await promise) // value

retry

Retry function with optional wait time

// Three attempts with 1 second wait
await retry(async () => {
    await doTheThing();
}, 3, 1000)