Previously, in this block https://frontend.cloudaccess.host/callback-in-javascript/. We have
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. Promise
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 then
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
See the Pen Promise.resolve by hieu (@phuchieuct93abc) on CodePen.