「 Article 」 March 08, 2020

Customize and handle a Promise

Words count 2.1k Reading time 2 mins. Read count 1000000

Promise

Promise is a very common object that web developers constantly face when developing website.

According to MDN, The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

Customize

To build a promise, we should understand the further operations for both success and fail. Example are given below

    function divide(a,b){
        return new Promise( function(resolve,reject) {
                if(b===0){
                    reject("divide by 0") // when the promise is failed
                    return
                }
                resolve(a/b) // when the promise processes succussfully
        })
    }

    divide(10,1)
     .then(res =>  console.log(`the result is ${res}`))
     .catch(err => console.log(err))
    //  log the result is 10

    divide(10,0)
     .then(res =>  console.log(`the result is ${res}`))
     .catch(err => console.log(err))
    // divide by 0

Handle Promise

As you can see above, it can be done by .then and .catch

Besides, there is an async/await method to deal with Promise.

This method is introduced in ES8. Basically, it is just a syntax sugar which means it serves the purpose with .then and catch but in a different form.

Note: await must be inside the async function

    const checkRes = async (a,b) =>{
        try {
            let res = await divide(a,b)
            console.log(res)
        } catch (error) {
            console.log(error)
        }

    }
    checkRes(10,2) // 2
    checkRes(10,0) // divide by 0
0%