How to Implement a Custom Promise in JavaScript ?
Last Updated :
30 Jan, 2024
A custom Promise in JavaScript encapsulates asynchronous operations. It takes two parameters, resolves and rejects functions, and executes an async task. Resolve is called on success with the result, while reject is called on failure with an error.
Using Class Syntax
In this approach, we are creating a custom promise using Class Syntax. The class encapsulates asynchronous operations, handling resolution, rejection, and chaining. It provides a concise and organized structure for promise implementation in JavaScript.
Syntax:
class Name {
constructor(var) {
this.var = var;
}
}
The Name class has a constructor that initializes an instance with a property var. This property stores a value passed during object creation, encapsulating it within the class instance.
Example: To demonstrate the CustomPromise class implements a basic promise with asynchronous resolution. The then method creates and returns a new promise, handling fulfilment or rejection asynchronously.
JavaScript
class CustomPromise {
constructor(executor) {
this.state = "pending";
this.value = null;
this.handlers = [];
const resolve = (result) => {
if (this.state === "pending") {
this.state = "fulfilled";
this.value = result;
this.handlers.forEach((handler) => {
handler.onFulfilled(result);
});
}
};
const reject = (error) => {
if (this.state === "pending") {
this.state = "rejected";
this.value = error;
this.handlers.forEach((handler) => {
handler.onRejected(error);
});
}
};
executor(resolve, reject);
}
then(onFulfilled, onRejected) {
return new CustomPromise((resolve, reject) => {
if (this.state === "fulfilled") {
setTimeout(() => {
try {
resolve(onFulfilled(this.value));
} catch (error) {
reject(error);
}
}, 0);
} else if (this.state === "rejected") {
setTimeout(() => {
try {
reject(onRejected(this.value));
} catch (error) {
reject(error);
}
}, 0);
} else {
this.handlers.push({ onFulfilled, onRejected });
}
});
}
}
const promise = new CustomPromise((resolve, reject) => {
setTimeout(() => resolve("Hello, GeeksforGeeks"), 500);
});
promise.then((result) => console.log(result));
OutputHello, GeeksforGeeks
Using Factory Function
A factory function is a function that returns an object or a function. In the context of a custom promise, a factory function creates and returns a custom promise object with specified behaviours.
Syntax:
function createRobot(name) {
return {
name: name,
talk: function () {
console.log('My name is '
+ name + ', the robot.');
}
};
}
Example: This createCustomPromise factory function generates a custom promise-like object with `then`, `catch`, and `finally` methods.
JavaScript
function createCustomPromise(delay, shouldResolve) {
return {
then(onFulfilled, onRejected) {
return createCustomPromiseInternal(
delay,
shouldResolve,
onFulfilled,
onRejected
);
},
catch(onRejected) {
return this.then(null, onRejected);
},
finally(onFinally) {
return this.then(
(result) => {
onFinally();
return result;
},
(error) => {
onFinally();
throw error;
}
);
},
};
}
function createCustomPromiseInternal(
delay,
shouldResolve,
onFulfilled,
onRejected
) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (shouldResolve) {
try {
resolve(
onFulfilled &&
onFulfilled(`
Promise resolved successfully
`)
);
} catch (error) {
reject(error);
}
} else {
try {
reject(onRejected && onRejected("Promise rejected"));
} catch (error) {
reject(error);
}
}
}, delay);
});
}
const promise = createCustomPromise(500, true);
promise
.then((result) => console.log(result))
.catch((error) => console.error(error))
.finally(() => console.log("Finally block executed"));
Output:
Promise resolved successfully
Finally bloxk executed
Similar Reads
How to Convert Callback to Promise in JavaScript ? Asynchronous programming in JavaScript often involves the use of callbacks. However, callbacks can lead to callback hell and make the code harder to read and maintain. Promises provide a cleaner way to handle asynchronous operations. Converting existing callback-based code to use promises can improv
2 min read
Implement polyfill for Promise.all() method in JavaScript The task is to write a polyfill for Promise.all methods in javascript. What is a Polyfill? A polyfill is a piece of computer code written to implement a feature in a browser that does not yet support it. It could be because the older version of the browser you are using, or the new version of the br
4 min read
JavaScript - How to Handle Errors in Promise.all? To handle errors in Promise.all(), you need to understand that it fails immediately if any of the promises reject, discarding all resolved values. This behavior can lead to incomplete operations and potential application crashes. The best way to manage errors in Promise.all() is by using .catch() in
3 min read
How to call promise inside another promise in JavaScript ? In JavaScript, to call promise inside another promise we first declare a promise using its basic syntax and further execute this promise then create another which is to be called inside the previous promise for its execution. Promise is basically a JavaScript object which is responsible for handling
3 min read
How to access the Value of a Promise in JavaScript In this article, we will see how to access the value of Promise in JavaScript. The Promise is a feature of ES6 introduced in 2015. The concept of Promises is generally used when we want to work asynchronously. The value of a Promise can be accessed in JavaScript using the following methods. Table of
2 min read
Explain Promise.all with async-await in JavaScript In JavaScript, Promise.all with async-await is used to handle multiple asynchronous operations concurrently. By combining Promise.all with await, you can wait for all promises to resolve or any to reject, ensuring that all asynchronous tasks are complete before proceeding with the next code executio
4 min read
JavaScript Promise Chaining Promise chaining allows you to execute a series of asynchronous operations in sequence. It is a powerful feature of JavaScript promises that helps you manage multiple operations, making your code more readable and easier to maintain.Allows multiple asynchronous operations to run in sequence.Reduces
3 min read
Explain Promise.any() with async-await in JavaScript In this article, we will try to understand how to implement the Promise.any() method with async-await in JavaScript using some theoretical explanations followed by some coding examples as well. Let us firstly quickly understand the working of Promise.any() method with some theoretical examples (incl
4 min read
Explain Promise.race() with async-await in JavaScript In this article, we will try to understand how we may implement Promise.race() method with async-await in JavaScript with the help of certain coding examples as well as theoretical explanations. Let us first quickly understand how we may implement Promise.race() method. This method is one of the mos
3 min read
How to wait for multiple Promises in JavaScript ? Waiting for multiple promises in JavaScript involves using Promise.all() or Promise.allSettled() methods. These methods accept an array of promises as input. Promise.all() waits for all promises to either resolve or reject, providing a single promise that resolves with an array of results or rejects
3 min read