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.
new Promise()
, Promise.resolve()
, and Promise.reject()
all creates a promise instance.
.then()
and .catch()
are used to react to the asynchronous value returned by the promise instance.
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.
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).
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With