@@ -96,35 +96,7 @@ const promisedData = promisedResponse.then(response => {
9696});
9797```
9898
99- If it seems confusing that there’s actually two Promises for the one JSON value, consider if we delayed
100-
101- ``` javascript
102- function callIn (timeout ) {
103- return {
104- then : (callback ) => setTimeout (callback, timeout)
105- };
106- }
107-
108- Promise .resolve (callIn (500 ));
109-
110- const promisedResponse = fetch (' https://swapi.dev/api/people/1/' );
111- const promisedData = promisedResponse .then (response => {
112- return {
113- then : (callback , reject ) => {
114- console .log (' reject' , reject);
115- setTimeout (() => {
116- callback (response .json ());
117- }, 1000 );
118- }
119- }
120- });
121- ```
122-
123- ### Async Await
124-
125- The same applies if the code is rewritten to use ` async await ` . The underlying objects are still Promises.
126-
127- ### Failure
99+ ### Failure recovery
128100
129101``` javascript
130102const fallbackData = {
@@ -138,48 +110,6 @@ fetch('https://swapi.dev/api/people/1/')
138110 .catch (() => fallbackData);
139111```
140112
141- ### Caching
142-
143- ``` javascript
144- function sideEffect (send , transform ) {
145- return (value ) => ({
146- then (resolve ) {
147- const transformed = transform (value);
148- resolve (transformed);
149- send (transformed);
150- }
151- })
152- }
153-
154- function cacheStorer (cache , key , transform ) {
155- return sideEffect (value => cache .set (key, transform (value)));
156- }
157-
158- function localStorageStorer (key ) {
159- return sideEffect (value => window .localStorage .setItem (key, value));
160- }
161-
162- const cachedValues = new WeakMap ();
163- function useCacheKey (cache , key ) {
164- return [cache .get .bind (cache, key), cache .set (cache, key)];
165- }
166-
167- function fetchCached (url ) {
168- const [read , write ] = useCacheKey (cachedValues, url);
169-
170- const promise = read (url);
171- if (promise) {
172- return promise;
173- } else {
174- return fetch (url).then (
175- sideEffect (write, Promise .resolve ),
176- sideEffect (write, Promise .reject )
177- );
178- }
179- }
180- function fetchCached (url ) {
181- return Promise .resolve (cachedValues .get (url) || fetch (url).then (cacheStorer (cachedValues, url)));
182- }
183- ```
113+ ### Async Await
184114
185- ### Chaining
115+ The same applies if the code is rewritten to use ` async await ` . The underlying objects are still Promises.
0 commit comments