AppDividend
Latest Code Tutorials

Javascript Promise Resolve Example | Promise.resolve() Tutorial

0 48

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

Javascript Promise Resolve Example | Promise.resolve() Tutorial is today’s topic.  The Promise.resolve() method returns the Promise object that is resolved with the given value.  If the value is the promise, that promise is returned; if the value is a thenable, then returned promise will “follow” that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.

Javascript Promise Resolve Example

The syntax for Javascript Promise.resolve() is following.

Promise.resolve(value);

The value parameter is resolved by this Promise. Can also be the Promise or a thenable to resolve.

The Promise that is resolved with the given value or the promise passed as value if the value was a promise object. The static Promise.resolve() function returns the Promise that is resolved.

Let us take a simple example. Write the following code inside the app.js file.

// app.js

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

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

Save the file and go to the terminal and run the file by typing the node app command.

 

Javascript Promise Resolve Example | Promise.resolve() Tutorial

Here, the p1 promise is thenable, and it eventually returns the value AppDividend.

Resolving an array

Let us take a simple example which resolves an array.

// app.js

const p1 = new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
	setTimeout(() => {
		resolve([18, 21, 22]);
	}, 1000);
});

p1.then(values => { 
	console.log(values[0]);
});

It will return the 18 value.

 

Javascript Promise Resolve Example

Resolving another Promise

Let us take the following example.

// app.js

const p = Promise.resolve(21);

const p1 = new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
	setTimeout(() => {
		p.then(value => console.log(value));
	}, 1000);
});

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

Here, we are resolving promise inside a promise. So the final output will be the value of the first promise.

 

Promise.resolve() Tutorial

Finally, Javascript Promise Resolve Example | Promise.resolve() 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.