Chapter 3. Working with Standard Promises
Weâve covered the standard Promise API and some basic scenarios, but like any technology, thatâs only part of the story. Now itâs time for scenarios youâll encounter and techniques you can use while writing real-world applications.
The Async Ripple Effect
Async functions and promises are contagious. After you start using them they naturally spread through your code. When you have one async function, any code that calls that function now contains an async step. The process of other functions becoming async by extension creates a ripple effect that continues all the way through the call stack. This is shown in Example 3-1 using three functions. Look how the async ajax
function forces the other functions to also be async.
Example 3-1. The async ripple effect
showPun
().
then
(
function
()
{
console
.
log
(
'Maybe I should stick to programming'
);
});
function
showPun
()
{
return
getPun
().
then
(
function
(
pun
)
{
console
.
log
(
pun
);
});
}
function
getPun
()
{
// Assume ajax() returns a promise that is eventually
// fulfilled by json for {content: 'The pet store job was ruff!'}
return
ajax
(
/*someurl*/
).
then
(
function
(
json
)
{
var
pun
=
JSON
.
parse
(
json
);
return
pun
.
content
;
});
}
// Console output:
// The pet store job was ruff!
// Maybe I should stick to programming
The work to retrieve and display a pun is divided into three functions: showPun
, getPun
, and ajax
. The functions form a chain of promises that starts with ajax
and ends with the object ...
Get JavaScript with Promises now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.