How to use Promise【JavaScript】

Tomoharu Tsutsumi
2 min readDec 1, 2019

Promise is an object for asynchronous work. A long time passed since I studied Promise for the first time. When I used this the other day, I thought I forgot it a little bit. I will summarise in order to memorise it.

The fundamental form of Promise

We must remember the basic form. It is below.

function calc(n){
return promise = new Promise((resolve, reject) => {
if( n * 2 >= 10)
resolve(n * 2)
else
reject('too small')
end
})
}
calc(10).then((n) => {
console.log(n)
}).catch((error) => {
console.log("error!")
console.log(error)})

Promise needs to make an instance and the instance has two call back method. They are resolve and reject. These two methods can have arguments and the arguments can be used in ‘then function.’ When resolve function is triggered, then function works, and when reject function is triggered, catch function works. In this example, when argument n * 2 is bigger than 10, resolve function is triggered, and the argument n * 2 is send to then function. Finally, n * 2 is displayed. On the other hand, when n * 2 is not bigger than 10, reject function is triggered, and ‘too small’ is send to catch function as an argument. ‘too small’ and ‘error’ are displayed.

Promise chain

You can connect functions in Promise. It is called ‘Promise chain’. The example is below.

function calc(n){
return promise = new Promise((resolve, reject) => {
if( n * 2 >= 10)
resolve(n * 2)
else
reject('too small')
end
})
}
let add = (n) => {
console.log(n)
return n + 100
}
calc(10).then(add).then((n) => {
console.log(n)
}).catch((error) => {
console.log("error!")
console.log(error)})

In this case, add function is added. The return number of calc is send to add function and the function adds 100 to the number. Also, then((n) => {}) is triggered. 110 is displayed. If the error happens, what happens? For example, n = 1. In that case, add function is not called. After calc function works, catch function is triggered.

Promise is not difficult. Practice it many times and have a good relationship with Promise.

If you think this article good, please follow me!

I update articles once a week!

https://twitter.com/tomoharutsutsum

--

--

Tomoharu Tsutsumi

Senior Software Engineer at two industry-leading startups ( Go | Ruby | TypeScript | JavaScript | Gin | Echo | Rails | React | Redux | Next)