Open In App

How to Return an Empty Promise in TypeScript ?

Last Updated : 23 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In TypeScript, you can return an empty promise to create an empty asynchronous task.

There are mainly two ways that can be used to create empty promises in TypeScript as listed below.

By using the Promise.resolve() method

In this approach, we will directly use the Promise.resolve() method instead of creating an instance of a new Promise() object to create an empty object or a dummy asynchronous task.

Syntax:

Promise.resolve();

Example: The below code example will explain the use of the promise.resolve() method creates an empty promise.

Javascript
function createEmptyPromise(): Promise<void> {
    return Promise.resolve();
}

createEmptyPromise().then(() => {
    console.log(`Empty Promise created
using Promise.resolve() method.`);
});

Output:

Empty Promise created using Promise.resolve() method.

By immediately resolving the promise

In this method, we will resolve the promise immediately after declaring the instance of the new Promise() object using the Promise.resolve() method and create an empty promise.

Syntax:

new Promise((resolve)=>{resolve();});

Example: The below code example creates an empty promise by immediately resolving it.

Javascript
function createEmptyPromise(): Promise<void> {
    return new Promise((resolve) => {
        resolve();
    });
}

createEmptyPromise().then(() => {
    console.log(`Empty Promise is created
by immediately resolving 
it after creating instance
of Promise object.`);
});

Output:

Empty Promise is created by immediately resolving it after creating instance of Promise object.

Using async/await to Return an Empty Promise

You can also leverage async and await syntax to return an empty promise in TypeScript. This method offers a more modern and concise way to handle asynchronous operations.

Example: In this example we defines an async function createEmptyPromise() returning a void Promise. Upon resolution, it logs “Empty Promise created using async/await.”

JavaScript
async function createEmptyPromise(): Promise<void> {
    // No asynchronous task is performed
}

createEmptyPromise().then(() => {
    console.log("Empty Promise created using async/await.");
});

Output:

"Empty Promise created using async/await."

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads