Promises: Jogesh K. Muppala

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 5

Promises

Jogesh K. Muppala
Promise
• Promise is a mechanism that supports
asynchronous computation
• Proxy for a value not necessarily known when the
promise is created:
– It represents a value that may be available now, or in
the future, or never

2
Promise
Promise
(pending)

resolve/fulfill reject

Promise Promise
(resolved/fulfilled) (rejected)

new Promise ( function (resolve, reject) { . . . } );

3
Promise Example
. . . getDishes(): Promise<Dish[]> {
getDishes()
return new Promise (
function(resolve, reject) {
.then ( function(result) {
// do something
if (successful) {
} ) resolve(result);
}

.catch ( function(error) { else {


reject(error);
}

} ); });
}

4
Why Promises?
• Solves the callback hell (heavily nested callback
code) problem
• Promises can be chained
• Can immediately return:
– Promise.resolve(result)
– Promise.reject(error)

You might also like