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

@mrspartak/promises

v1.0.0

Published

Promise utilities

Downloads

332

Readme

🔧 Typescript promise utilities

@mrspartak/promises is toolbelt with useful promise utilities that also utilizing a power of Typescript

Contents

Installation

# yarn
yarn add @mrspartak/promises
# npm
npm i @mrspartak/promises
# pnpm
pnpm add @mrspartak/promises
# bun
bun add @mrspartak/promises

Functions

to - Simplified Promise Handling with Tuples

This function helps reduce the verbosity of try/catch blocks by allowing you to handle promise results inline. Inspired by Go's error handling, it returns a tuple with either an error or the result, making your asynchronous code cleaner and more maintainable.

Pros:

  • ✨ Cleaner Code: Reduces the verbosity and complexity of using multiple try/catch blocks, leading to more readable and maintainable code.
  • 📝 No Need for Predefined Variables: Eliminates the need to declare variables before the try/catch block, simplifying variable management and ensuring proper typing.
  • 📏 Forces a Consistent Error Handling Pattern: Encourages a unified and specific way of dealing with errors, improving code consistency across the project.
import { to } from "@mrspartak/promises"
import { api } from "./api"

// Simple tuple destructuring
const [apiError, user] = await to(api.get("/me"))
if (apiError) {
  // Handle error
}

// Using finally
$component.isLoading = true
const [apiError, status] = await to(api.post("/me/status", { status: "online" }), () => {
  $component.isLoading = false
})
if (apiError) {
  // Handle error
}

delay - Pause Execution for a Specified Time

The delay function pauses the execution of your code for a specified number of milliseconds. This can be useful in various scenarios, such as waiting for an operation to complete, introducing a delay between retries, or simply pausing execution for debugging purposes.

! The function has alias sleep

import { delay, sleep } from "@mrspartak/promises"
import { parsePage } from "./parser"

for (let i = 0; i < 10; i++) {
  // Parse the page and wait for 1 second before parsing the next page
  const pageData = await parsePage(i)
  await delay(1000)
}

// You can also use alias sleep instead of delay
await sleep(1000)

timeout - Timeout a Promise

The timeout function allows you to set a maximum time for a promise to resolve. If the promise does not resolve within the specified time, an error is thrown.

import { timeout } from "@mrspartak/promises"
import { api } from "./api"

// Can be used as a race condition
const [error, user] = await timeout(api.getUser(), 1000)
if (error) {
  // error can be either a timeout error or an error from the api
}

deferred - Create a Deferred Promise

The deferred function allows you to manually resolve or reject a promise at a later time. This can be useful in scenarios where you need to control the timing of the resolution or rejection, such as in testing or when dealing with asynchronous operations that don't natively return promises.

import { deferred } from "@mrspartak/promises"

// Create a deferred promise
const { promise, resolve, reject } = deferred<void>()

setTimeout(() => {
  // Resolve the promise
  resolve()
}, 1000)

await promise // Will wait for 1 second before resolving

retry - Retry a Promise-Returning Function

The retry function allows you to retry a promise-returning function a specified number of times with an optional delay between attempts if it fails. This can be useful for handling transient errors, such as network requests that may occasionally fail.

import { retry } from "@mrspartak/promises"
import { apiCall } from "./api"

// Retry the API call up to 3 times with a delay of 1000 milliseconds between attempts
const [error, result] = await retry(() => apiCall(), 3, { delay: 1000 })
if (error) {
  // error will always be an error returneb by a promise rejection
}

duration - Measure the Time Taken for a Promise to Resolve

The duration function allows you to measure the time it takes for a promise to resolve or reject. This is useful for performance monitoring and debugging asynchronous operations in your code.

import { duration } from "@mrspartak/promises"
import { apiCall } from "./api"

// Measure the time taken to resolve the API call
const [error, result, time] = await duration(apiCall())
if (error) {
  // Handle error
}