Introduction
In web development, asynchronous (aka, async) operation, such as API calling is inevitable for developer to not work with, and the basic foundation knowledge we need to know is Promise.
Promise is a special JavaScript object that produces a value after async operation completes successfully, or even an error, such as timeout, connection error, wrong API URL, and so on.
This article is a simple explanation of Promise.
Creating a Promise Object
Below is the example how to create a Promise
Object.
let promise = new Promise(function(resolve, reject){
// perform asynchronous computation
resolve("Give result")
})
// or using arrow function
let promiseTwo = new Promise((resolve, reject) => {
resolve("Give result")
})
// or using Promise shortcut function
let promiseThree = new Promise.resolve("Give result")
Promise Handler
In order to get the asynchronous computation result, Promise
needs to use .then
and return the result. Let's use above example and below code describes how to use .then
method.
let promise = new Promise(function (resolve, reject) {
// return message after 1 sec
setTimeout(function () {
resolve("Give result after 1 sec");
}, 1000);
});
promise.then((res) => {
console.log(res); // output: "Give result after 1 sec"
});
Maybe you already guessed that if the Promise
object has resolve
property, by looking at the above parameter, we should also have reject
property. You are definitely right !
Moreover, those arguments (resolve
and reject
) are callbacks provided by JavaScript.
- resolve(value) - return the
value
object if async computation run successfully. - reject(error) return the
error
object if an error has occurred.
Let's expand the above example with reject
callback.
let promise = new Promise(function(resolve, reject){
reject("Error happened")
})
promise.then(res => {
console.log(res);
}).catch(err => {
// reject will be caught by .catch
console.log(err); // output: "Error happened"
})
Deep Dive into Promise Constructor
These below are all Promise
object returns from new Promise
constructor:
-
state
— initial value is "pending",- then changes to "fulfilled" when
resolve
is called, - or changes to "rejected" when
reject
is called.
- then changes to "fulfilled" when
-
result
— initial value isundefined
,- then changes to
value
whenresolve(value)
is called, - or changes to
error
whenreject(error)
is called.
- then changes to
Important Notes: Promise should execute only one, either
resolve
orreject
. Once one state is changed, we can't change to other state. Any further execution toresolve
orreject
will be ignored.
let promise = new Promise(function(resolve, reject){
reject("Error happened!")
resolve("Change my mind, error didn't happen") // will be ignored
})
promise.then(res => {
console.log('resolve: ', res);
}).catch(err => {
console.log('rejected:', err); // output: "rejected: Error happened!"
})
Conclusion
Promise
in JavaScript performs asynchronous computation and it requires resolve
or reject
property to return statement or value. In order to get the value from our Promise
, we can use then
and catch
method for resolved and rejected value respectively.
Comments (0)