Deno World
Published in

Deno World

Deno nuggets: Auto-rejecting promises

This article is a part of the Deno nuggets series, where each article attempts to suggest a pointed solution to a specific question that can be read in less than a minute. There is no ordering of nuggets.

Problem

How to auto-reject a promise after a given time?

const p = new Promise((res, rej) => {});
try {
await p;
} catch (e) {
//auto rejects after a given amount of time
}

Solution

To auto-reject a promise, we can use Deno’s standard library’s deadline module.

Imports

An import of deadline() API and DeadlineError (error) from Deno’s standard library’s async module is required:

import {
deadline,
DeadlineError,
} from "https://deno.land/std/async/deadline.ts";

Auto-reject any promise

The async deadline() API takes a promise as input and auto-rejects it after a given amount of time (in milliseconds). The deadline() API creates an additional promise that rejects itself after timeout. The deadline() API simply uses JavaScript’s core Promise.race API to create a race between input promise and created promise. An error called DeadlineError would be raised whenever promise is auto-rejected.

The following code auto-rejects a promise ‘p’ after provided seconds that would resolve itself after 3 seconds:

import {
deadline,
DeadlineError,
} from "https://deno.land/std/async/deadline.ts";
const p = new Promise((r) => setTimeout(r, 3000));
try {
await deadline(p, Number(Deno.args[0]));
console.log("Promise resolves");
} catch (e) {
if (e instanceof DeadlineError) {
console.error("Promise auto-rejected");
} else {
console.error("Promise rejected due to other errors");
}
}

The output of some runs is as follows:

$ deno run app.ts 2000 
Promise auto-rejected
$ deno run app.ts 4000
Promise resolves

This story is a part of the exclusive medium publication on Deno: Deno World.

--

--

--

The one and only exclusive medium magazine with 200+ articles on Deno

Recommended from Medium

Node.js Tips — Express Errors, URLs, Parameters and Writing Files

Vue Router 4–Named Routes and Multiple router-views

How to Let Users Download JavaScript Array Data as a CSV on Client-Side?

Install react-native-maps with Gradle 3 on Android

Developing Vue Apps with the Quasar Library — Button Groups

JS10 — Ten Javascript fundamental topics you should know

Immutable state in NGXS. Part II.

Complete Dive Into TypeScript: Part 1

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mayank Choubey

Mayank Choubey

Deno, Node.js, etc.

More from Medium

A comprehensive guide to HTTP clients in Deno

Deno on Windows: Hello world HTTP server

Deno nuggets: Write raw data on console

An ultimate guide to Deno