From ddce1bcd28c4fd0d756694fc2f4e6e77af2e4600 Mon Sep 17 00:00:00 2001 From: Clark Fischer Date: Mon, 16 Jan 2023 07:35:23 -0800 Subject: [PATCH] Add async `setImmediate` util Adds an async/promise-based version of `setImmediate`. Note that, despite being poorly adopted, `setImmediate` is polyfilled, and should be more performant than `sleep(0)`. Signed-off-by: Clark Fischer --- spec/unit/utils.spec.ts | 34 ++++++++++++++++++++++++++++++++++ src/utils.ts | 14 +++++++++++--- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/spec/unit/utils.spec.ts b/spec/unit/utils.spec.ts index 8104cba08..caf15a43e 100644 --- a/spec/unit/utils.spec.ts +++ b/spec/unit/utils.spec.ts @@ -1,3 +1,19 @@ +/* +Copyright 2023 The Matrix.org Foundation C.I.C. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + import * as utils from "../../src/utils"; import { alphabetPad, @@ -587,4 +603,22 @@ describe("utils", function () { expect(utils.isSupportedReceiptType("this is a receipt type")).toBeFalsy(); }); }); + + describe("sleep", () => { + it("resolves", async () => { + await utils.sleep(0); + }); + + it("resolves with the provided value", async () => { + const expected = Symbol("hi"); + const result = await utils.sleep(0, expected); + expect(result).toBe(expected); + }); + }); + + describe("immediate", () => { + it("resolves", async () => { + await utils.immediate(); + }); + }); }); diff --git a/src/utils.ts b/src/utils.ts index 5134c8a4d..6a15e9744 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,6 +1,5 @@ /* -Copyright 2015, 2016 OpenMarket Ltd -Copyright 2019 The Matrix.org Foundation C.I.C. +Copyright 2015, 2016, 2019, 2023 The Matrix.org Foundation C.I.C. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -392,13 +391,22 @@ export function ensureNoTrailingSlash(url?: string): string | undefined { } } -// Returns a promise which resolves with a given value after the given number of ms +/** + * Returns a promise which resolves with a given value after the given number of ms + */ export function sleep(ms: number, value?: T): Promise { return new Promise((resolve) => { setTimeout(resolve, ms, value); }); } +/** + * Promise/async version of {@link setImmediate}. + */ +export function immediate(): Promise { + return new Promise(setImmediate); +} + export function isNullOrUndefined(val: any): boolean { return val === null || val === undefined; }