ASYNCHRONOUS
NETWORKING Networking with XMLHttpRequest()
• Client-Server Model + AJAX
Copyright By PowCoder代写 加微信 powcoder
• Concurrency & JS
• NetworkingwithXMLHttpRequest()
• Networking with Promises & fetch()
• Networking with async/await & fetch()
RECAP Servers
The JS event loop lets us perform asynchronous execution.
Still uncertain about how to do that. XMLHttpRequest() is one way
Latest News API Super cool cats API
A minimal example
• Built-in API
• Allows creation of a handle representing a request
• Asynchronous by default
• Many knobs and dials (see the docs for a full discussion)
• Error-Handling through exceptions and status codes
• Network errors, failure-to-send errors are exceptions
• Normal HTTP errors communicated through xhr.status
• Customisation via callbacks
• Main callbacks: xhr.onload, xhr.onerror
• Fallen out of favour
• Need to know for legacy codebases
BASIC XMLHTTPREQUEST DEMO
See examples/basic-xmlhttprequest
Expected Errors
• Authentication errors
• Bad parameter errors
• Non-existent domain errors
• All checked through HTTP status codes
• 4xx for not using an API correctly • 5xx for internal server errors
• HTTP 200 means no error
HANDLING PROBLEMS Unexpected Errors
• Network connectivity issues
• Remote connection suddenly
• Timeouts
• Need to be handled by try/catch blocks
• Often the best strategy is to retry (with exponential back-off)
XMLHTTP ERROR-HANDLING DEMO
See examples/xmlhttp-error-handling
AVOIDING CALLBACK HELL
• Callback Hell: deep nesting of callbacks
• Often a result of:
• Many different people working on code
• Ad-hoc decision making
• Software Engineering Principles still apply:
• SRP – functions do a single thing only
• DRY – repetitive actions placed into a
• Let bundlers minimise your code for you
• Flat > Nested:
• Callbacks should be named functions
• Lambdas for easy one-liners
Image Credits:
IMPROVING Servers
Finally have a method of making an AJAX webapp
Setting up an XMLHttpRequest seems tedious and error-prone Can we do better?
Latest News API Super cool cats API
• MakingasynchronousnetworkrequestswithXMLHttpRequest() • Error-handlingstrategies
• Avoiding callback hell
• Coming Up Next: • Promises
• Networkingwithfetch()
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com