Previously, in this block https://frontend.cloudaccess.host/callback-in-javascript/. We have learn what is callback and what is Promise as well as the difference between them. To continue with Promise, today we gonna continue talk deeply about Promise and how to use it effectively.

Basic usage

The basic usage of promise is we create a new Promise object. In this constructor, we have to pass 2 params, resolver and reject. Both of them are just the Promise’s syntax, it’s not our callback function. In side the Promise, we do something, execute some logic asynchronously. And then when we want to return the value, we will call resolver(value) or reject(value).

var promise = new Promise(function(resolver,reject){
    setTimeout(function(){
        resolver("finished")
    },2000)
})

By do this, we have already triggered the timeout. But one important thing is when the timer is finished, the value “finished” is held by `promise`. Therefore, to archive that value. we need to call then method. `Then` method receive a callback, that callback has one input param. the value finished is passed into input param of that callback function. Something like this

See the Pen Basic_Promise by hieu (@phuchieuct93abc) on CodePen.

Beside this basic usage, we still have more usage which are useful in some scenario

Promise.all

Promise.all is used when we want to run multiple promises parallelly and notify when all of them are solve or reject. So that it’s usually used for getting data from multiple resources parallelly and combine the data together. Eventhough the promises are finished not in the same order (the 1st promise are resolved after the second one), Promise.all still put the result in exactly the order we defined

See the Pen Promise.all by hieu (@phuchieuct93abc) on CodePen.

Promise.race

In contrast with Promise.all is resolved when all promises are resolved, Promise.race only is resolved when the first callback is resolve.

See the Pen Promise.race by hieu (@phuchieuct93abc) on CodePen.

Promise.reject & Promise.resolve

Promise.reject & Promise.resolve are used when we want to do something asynchronously but want to keep return Promise object. It’s handy when we’re required to return a Promise but we don’t have any asynchronous task. Instead of creating a new Promise, we can easily return Promise.reject or Promise.resolve

See the Pen Promise.resolve by hieu (@phuchieuct93abc) on CodePen.

Leave a Reply

Your email address will not be published.