AppDividend
Latest Code Tutorials

Javascript Promise Reject Example | Promise.reject() Tutorial

0 43

Get real time updates directly on you device, subscribe now.

Javascript Promise Reject Example | Promise.reject() Tutorial is today’s topic. The Promise.reject() method returns the Promise object that is rejected with a given reason. The static Promise.reject() function returns the Promise that is rejected. For debugging purposes and selective error catching, it is useful to make reason an instanceof Error.

Javascript Promise Reject Example

The syntax for Javascript Promise.reject() method is following.

Promise.reject(reason);

The parameter reason is why this promise rejected.

Let us take a simple example.

// app.js

const p1 = new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
	setTimeout(() => {
		reject('fail promise');
	}, 1000);
});

p1.catch(error => { 
	console.log(error);
});

Here, we are rejecting the promise, and then we call the catch method on that promise to catch the error and log that error in the console.

The output is following.

 

Javascript Promise Reject Example | Promise.reject() Tutorial

We can also debug the error, if throw an instanceof Error object. Take a look at the following code.

// app.js

const p1 = new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
	setTimeout(() => {
		reject(new Error('Promise failed'));
	}, 1000);
});

p1.then(error => { 
	console.log(error);
});

The output is following.

 

Promise.reject() Tutorial

Here, we are getting the detailed Error Stack Trace.

Finally, Javascript Promise Reject Example | Promise.reject() Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.