Asynchronous programming
-
The difference between synchronous and asynchronous
-
Synchronization: Execute sequentially, send requests to the server –> the client does other operations
-
Asynchronous: Execute separately, send a request to the server ==> perform other operations at the same time
-
Native xmlhttprequest
-
four steps
-
create ajax object
var a=new xmlhttprequest();
-
Set the data transmission method (get, post), open the connection open()
ajax object.open("method","url","synchronous false/asynchronous true")
-
get response data
Attribute Description onreadystatechange This function will be called when the readystate changes responsetext Get the response data in string format responsexml Get the response data in the form of xml readystate 0: The request is not initialized 1: The server connection has been established 2: Request processing 3: Request processing 4: The request has been completed and the response is ready status 200: ok 404: Page not found -
Send https request: ajax.send()
-
-
Actual operation data exchange format [cannot cross-domain]:
-
Get the content of the xml file and render it beautifully to the page
-
<button>Get Data</button> <table></table> <script> document.getElementsByTagName("button")[0].onclick=function(){ var ajax=new XMLHttpRequest; ajax.open("get","work1.xml",true); ajax.onreadystatechange=function(){ if(ajax.status==200 & amp; & amp;ajax.readyState==4){ xixi(ajax. responseXML); } } ajax. send() } function xixi(obj){ var table="<table><tr><th>name</th><th>age</th><th>address</th></tr>" var xml=obj.getElementsByTagName("xi"); for(i=0;i<xml.length;i++){ table + =`<tr><td>${xml[i].getElementsByTagName("name")[0].childNodes[0].nodeValue}</td> <td>${xml[i].getElementsByTagName("age")[0].childNodes[0].nodeValue}</td> <td>${xml[i].getElementsByTagName("address")[0].childNodes[0].nodeValue}</td></tr>` } document.getElementsByTagName("table")[0].innerHTML=table; } </script>
-
** Get the content of the json file and render it to the page
-
<button>Get Data</button> <table></table> <script> document.getElementsByTagName("button")[0].onclick=function(){ //Native ajax, 4 steps // 1. Create an ajax object var ajax=new XMLHttpRequest; // 2. Set the request method, address, synchronous or asynchronous ajax.open("get","work.json",true); // 3. Get the corresponding data // Trigger function if request state changes ajax.onreadystatechange=function(){ // If the request status is 4, it means the request is successful, and the data is returned, and the server-side page is accessed normally if(ajax.readyState==4 & amp; & amp;ajax.status==200){ // Call the function, pass actual parameters, ajax object data in string format xixi(ajax. responseText); } } // 4. Send request ajax. send() } function xixi(obj){ var table="<table><tr><th>name</th><th>age</th><th>hobbies</th></tr>" //Deserialization ==> convert json format to js object format var xml=JSON. parse(obj); //The json data is stored in the way of writing objects in the array, so loop the array and traverse each object for(i in xml){ table + = `<tr><td>${xml[i].name}</td> <td>${xml[i].age}</td> <td>${xml[i].ah}</td></tr>` } //Put the stitched form on this page to display document.getElementsByTagName("table")[0].innerHTML=table; } </script>
-
data structure:
Object structure: {"key":"value","key":"value"} Array structure: [value,value]
-
Notes on json syntax:
-
Attribute names must be wrapped in double quotes;
-
Values of string type must be wrapped in double quotes;
-
Single quotes for strings are not allowed in JSON;
-
Comments cannot be written in JSON;
-
The outermost layer of JSON must be in object or array format,
-
You cannot use undefined or functions as JSON values.
-
-
The relationship between json and js objects
-
JSON is a string representation of JS objects, which uses text to represent the information of a JS object, essentially a string.
js object: var obj = {a: 'Hello', b: 'world'} json: var json = '{"a": "Hello","b": "wor1d"}'
-
-
Convert between json and js
-
To convert from a JSON string to a JS object, use the JSON.parse() method:
var obj = json.parse('{"a": "he11o","b": "world"}'); //The result is {a:'He11o', b:'wor1d'}
-
To convert from a JS object to a JSON string, use the JSON.stringify() method:
var obj = json. stringify({a: 'Hello'. b:'world'}): //The result is '{"a": "hello","b": "world"}
-
-
Serialization and deserialization
-
The process of js–>json is called serialization, and the json.stringify() function is called a serialization function.
-
The process of json–>js is called deserialization, and the json.parse() function is called the deserialization function.
-
-
The advantages of json over xml: convenient, small and fast
-
-
jquery ajax
-
property name value/description async Boolean value, indicating whether it is asynchronous, the default is true type request type (get/post) url request address, the default current page data data sent to the server datatype Data type of server response beforesend(xhr) send request The function that was run before error(xhr,status,error) The function that the request failed to run success(result,status,xhr) Request function to run successfully complete(xhr,status) request Function to run on completion (called after both successful and failed requests) -
Method Writing ajax $.ajax({type,url,datatype,success}) post $.post(url,data,fn) or $.post (···) get $.get(url,fn)
promise
Base
-
A new solution for asynchronous programming introduced by ES6. Syntactically, Promise is a constructor used to encapsulate an asynchronous operation and obtain its success or failure result
-
Promise constructor: Promise(excutor){}
-
Promise.prototype.then method
-
Promise.prototype.catch method
-
-
Commonly used in custom wrapper functions
-
Explanation: In the above code, we use the async function to define an asynchronous function foo, which internally uses the await keyword to wait for the fetch method to return the value of the Promise object. When the fetch method returns a successful result, it will continue to execute the following code and use await to wait for the value of the Promise object returned by the res.json() method. If no errors occur, the json object will eventually be printed to the console. If an error occurs, a try…catch statement can be used to catch the exception and print an error message.
-
advantage:
-
Safer code: Using the async/await method can avoid common errors, such as the scope of callback functions, the order of callback functions, callback hell, etc.
-
Improves the running efficiency of the code, because it can avoid the additional overhead brought by the callback function, and can better utilize the characteristics of the JavaScript engine, such as single-threaded execution.
-
You can directly use the then() and catch() methods of the Promise object, which is convenient for code writing and maintenance.
-
practical:
-
// The first type var Promise = new Promise((resolve, reject) => { if (operation succeeded) { // Execute after success resolve(value){} } else { // Execute after failure reject(error){} } }) // second type Promise. then(function (value) { // success }, function (value) { // fail }) ?
-
//Instantiate the Promise object const p = new Promise(function(resolve,reject){ setTimeout(() => { /* let data = 'data' resolve(data)//Execute resolve to indicate that the call is successful */ let data = 'error' reject(data)//Executing reject indicates that the call failed, and execute the second callback function in .then }, 1000); }) ? //Call the then method of the promise object p.then(function(value){ console.log(value)//after executing resolve }, function(reson){ console.log(reson)//after executing reject }) ? ? //Promise encapsulates AJAX request //Interface address: https://api.apiopen.top/getJoke const p =new Promise((resolve,reject) => { //1. Create an object const xhr = new XMLHttpRequest() //2. Initialization xhr.open("GET","https://api.apiopen.top/getJoke") //3. Send xhr. send() //4. Binding event xhr.onreadystatechange = function(){ if(xhr. readyState === 4){ if(xhr.status>=200 & amp; & amp;xhr.status<300){ //The request is successful resolve(xhr. response) }else{ //Request failed reject(xhr. response) } } } }) //Extract the request result and further process it outside instead of internally p.then(function(value){ console. log(value) }, function(reason){ console. error(reason) }) copy code //Create promise object const p = new Promise((resolve,reject)=>{ setTimeout(() => { resolve('data') //reject('error') }, 1000); }) //The return result of the then method is a Promise object, and the state of the object is determined by the execution result of the callback function //1. If the result returned in the callback function is a non-Promise type attribute (number, string, undefined, etc.), the status is successful, and the return value is the successful value of the object //2. If the return result is a promise object, what is the status type of the promise object? //3. If an error is thrown, the promise returns rejected, and its value is the thrown value const result = p.then(value => { //1. Properties of non-promise types return 123//execution, its status is successful, and the success value of result is 123 //2. is a promise object return new Promise((resolve,reject)=>{ resolve('OK') }) //3. Throw an error throw new Error("Error") }, reason => { console. warn(reason) }) //4. Chain call Nested asynchronous tasks p.then(value=>{ ? }, reason => { ? }).then(value=>{ ? }, reason => { ? }) console. log(result) copy code Promise practice //Import fs module const { rejects } = require("assert") const fs = require("fs") const { resolve } = require("path/win32") ? /* fs.readFile('file.md',(err,data1)=>{ fs.readFile("file2.md",(err,data2)=>{ fs.readFile("file 3.md",(err,data3)=>{ let result = data1 + '\r\\ ' + data2 + '\r\\ ' + data3 console. log(result) }) }) }) *///Traditional method implementation is easy to cause callback hell ? ? //Using Promise implementation const p = new Promise((resolve,reject)=>{ fs.readFile('file.md',(err,data)=>{//The first asynchronous task resolve(data) }) }) ? p.then(value=>{//value first file content //To avoid callback hell, create a promis object again, raise it, and then again return new Promise((resolve,reject)=>{//The second asynchronous task fs.readFile('file 2.md',(err,data)=>{//data second file content resolve([value,data])//Success, the return is also successful }) }) }).then(value=>{//an array containing file and file 2 contents return new Promise((resolve,reject)=>{//The third asynchronous fs.readFile('file 3.md',(err,data)=>{//data third file content value.push(data)//array push resolve(value)//Successful return is also successful }) }) }).then(value=>{//Array of all files console.log(value.join('\r\\ ')) }) ? copy code Pormise object catch method const p = new Promise((value,reject)=>{ setTimeout(() => { reject("Error!") }, 1000); }) /* p.then(value=>{},reason=>{ console. error(reason) }) */ //then method does not specify the first parameter, namely catch p.catch(reason=>{ console. warn(reason) })
async/await
Base
Core: The core idea of async/await is to let asynchronous code execute like synchronous code, and convert asynchronous operations into synchronous operations. In this way, it is no longer necessary to use callback functions, but try…catch statements can be used to process the results of asynchronous operations.
practical
-
Example:
async function foo() { try { const res = await fetch('https://api.example.com/user') const json = await res.json() console. log(json) } catch (error) { console. error(error) } } ? // async: identification // await waits for the execution to complete later, and converts it into synchronization // try{ } function body // catch{ } exception function