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');});functionshowPun(){returngetPun().then(function(pun){console.log(pun);});}functiongetPun(){// Assume ajax() returns a promise that is eventually// fulfilled by json for {content: 'The pet store job was ruff!'}returnajax(/*someurl*/).then(function(json){varpun=JSON.parse(json);returnpun.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 returned ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access