ASYNCHRONOUS
NETWORKING Networking with Promises & fetch()
• Client-Server Model + AJAX
Copyright By PowCoder代写 加微信 powcoder
• Concurrency & JS
• NetworkingwithXMLHttpRequest()
• Networking with Promises & fetch()
• Networking with async/await & fetch()
RECAP Servers
XMLHttpRequest() provides one way to do asynchronous fetching.
ES2015 introduced a new way via fetch() and Promises
Before talking about fetch(), what is a Promise?
Latest News API Super cool cats API
ES2015 Promises
• Proxy for a future value
• Evaluated asynchronously
• Support chaining, branching, error handling
Image Credit: MDN Can be in one of 4 states:
• “Pending” – not evaluated yet • “Fulfilled” – Successfully
Other useful features:
• Can be orchestrated (Promise.all, Promise.race, etc.)
• “Promise-like” objects can be used with Promises
• “Rejected” – Failed to evaluate
• “Settled” – Either rejected or fulfilled
BASIC API USAGE Constructor:
• Accepts a callback that takes resolve() and reject() functions
• Fulfillment = calling resolve()
• Rejection = calling reject()
• Most common way to chain promises.
• Executes the next action if the previous one fulfilled
• Catch-all error handler for the chain above
• Nested execution of dependent operations
• Each .then() runs iff the previous promise fulfilled
• Any error/rejection that happens passed to the next-nearest .catch()
• After a .catch(), more operations can occur
• Every .then() returns a new promise
which wraps the previous one.
• Even if the given callback doesn’t
return a promise.
• Stored as Russian dolls
• But executed as a stack i.e. most-
nested happens first
• Multiple .then()’s on the same promise = branching
• When the parent promise is resolved, all .then()’s invoked in order
• Allows for complex control-flow on fulfillment
startMusic
startToPrepareDinner
watchSunset
ERROR-HANDLING
• Errors/Exceptions always cause rejections
• Explicit rejections done via calling reject()
• Any exceptions cause an implicit rejection
• .catch()clausescanhandle errors or pass them to the next .catch() by rethrowing
• .finally()isalsoavailablethat will run regardless of if an error occurred or not
ERROR-HANDLING GOTCHAS
• Promises always asynchronous
• Current function context always completes before a Promise is settled
• This means Promises don’t work with try/catch like on the left!
• Good idea to add an event listener to the window to handle the unhandledrejection event
PROMISE ORCHESTRATION
• The Promise class has some utilities for easy orchestration
• Promise.all(): returns a promise that resolves iff all of the promises passed to it resolve
• Promise.allSettled(): returns a promise that resolves once all of the promises passed to it are resolved
• Promise.any(): returns a promise that resolves if at least one of the promises passed to it resolves
• Promise.race(): returns a promise which resolves as soon as one of the promises passed to it resolves
• Promise.reject(): immediately return a rejected promise with a value
• Promise.resolve(): immediately return a resolved promise with a value
PROMISE-LIKE OBJECTS (THENABLES)
• Any object or class with a then() considered “promise-like” or a “thenable”.
• Can be used with Promise chaining
• Useful for fine-grained control over how chaining works for custom types
THE FETCH API
• Promise-based native JS API to
download remote resources
• Resolves if a Response is received, even if the HTTP status code is not 200
• Rejects if there is any network error
• Access the result of the request via
chaining then()s
• Optional 2nd argument to fetch() can control the Request options e.g.
• Authentication • CORS
• HTTP method
PROMISE + FETCH DEMO
See examples/promise-fetch
XMLHttpRequest
• Works even on very old browsers • Gives large download progress
• Easily cancelled
FETCH LIMITATIONS
• Only works on browsers with Promise support (less of a problem nowadays)
• Promises not easily cancellable
• More complex functionality implemented via the Streams API which has a non-trivial learning curve
MOVING FORWARD Servers
fetch() is a very flexible and nice API to work with. However, chaining and callbacks still removes us from
writing code like we are used to. Can we do even better?
Latest News API Super cool cats API
• Promises
• UsingPromiseswithfetch()
• Coming Up Next:
• Networkingwithasync/await&fetch()
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com