Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion the use of resolve() and then() methods with Promise

Tags:

javascript

I was learning promises in JS and the use of resolve() and then() is a bit confusing me. So, as far as I understood, the promises serve as a wrapper for asynchronous operations and the reason to use promise is to ensure the easier chaining. Right? Then, the reason to use resolve() is that it points to the place where we get data and after that we do something with that data thanks to then(). Is that correct? if not can you explain why to use resolve() and then() in simple words.

like image 587
Pop Avatar asked Oct 17 '25 19:10

Pop


2 Answers

Promise, resolve, and reject

new Promise(), Promise.resolve(), and Promise.reject() all creates a promise instance.

Then and catch

.then() and .catch() are used to react to the asynchronous value returned by the promise instance.

What are the difference then?

new Promise() is to execute asynchronous operations. It must resolve or reject with a value.

Promise.resolve() and Promise.reject() is to wrap a value into a resolved or rejected promise value.

.then() is to react with a resolved promise with its value.

.catch() is to react with a rejected promise with its value.

Conclusion

All promises must be initiated with one of new Promise(), Promise.resolve(), or Promise.reject(). Only then you are able to use .then() or .catch().

Just think of it like normal English, you only use the word "then" after something is done (making a promise, for example).

like image 94
yqlim Avatar answered Oct 19 '25 10:10

yqlim


resolve and reject are just ways to tell the caller that your promise is completed (it's been resolved or rejected). .then can be used, but I prefer to use await when I can.

Using return new Promise( (resolve, reject) => {}); is a good way to wrap things to make then asynchrous which is awesome, but most of the time, if something returns a promise (like a lot of libraries are starting to do), then you can just await it. Same thing as calling .then on a promise (from a 10,000 foot level)

Example:

const myPromise = async () => {
	return new Promise( (resolve, reject) => {
  	setTimeout( () => {
    	resolve('im done!');
    }, 1000);
  })
}

// Use .then to call your promise in a 'callback way'
myPromise().then( text => console.log(text));

async function awaitThePromise() {
// using await to call your promise
	const result = await myPromise();
  console.log(result);
}

awaitThePromise();
like image 40
mwilson Avatar answered Oct 19 '25 10:10

mwilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!