Synchronous and asynchronous

Synchronization is to get the results directly, such as in the hospital registration room, to get the number to leave the window.

Asynchronous means you can’t get results directly, like you can go shopping while you’re waiting for your meal at a restaurant. You can go to the restaurant every 10 minutes and ask (polling). You can also scan the code to receive notifications on wechat (callback).

The callback

The relationship between asynchrony and callback:

Asynchronous tasks need to notify JS to get the results when they get them

B: How?

You can ask JS to leave a function address (phone number) to the browser

When the asynchronous task is complete, the browser calls the address of this function.

And pass the result as an argument to the function (it was ready to eat on the phone)

This is a callback function that I wrote for the browser to call

Note:

Asynchro doesn’t have to be just callbacks. You can use polling. Callbacks don’t have to be just asynchronous tasks, they can also be synchronous tasks.

Function f1() {console.log(" I am a function, not a callback ")} function f2(fn) {console.log(" I am a function, not a callback ")} f2(f1)Copy the code

The above f1 is not called, but F1 is passed to F2, which calls F1. F1 is the function to be called to F2. So F1 is a callback.

Determining synchronous and asynchronous (elementary)

A function is asynchronous if its return value is in one of the following internals:

setTimeout()
AJAX
AddEventListener()
Copy the code

You should never make AJAX synchronous.

function rollTheDice(fn) { setTimeout(() => { fn(parseInt(Math.random() * 6) + 1) }, RollTheDice ((x) => {console.log(x)})Copy the code

Method one: The callback takes two arguments

Fs. ReadFile (. / text, (error, data) = > {the if (error) {the console. The log (' failure '); return} console.log(data.toString()) })Copy the code

Method two: Use two callbacks

ajax('get','/1.json',data=>{},error=>{})
Copy the code
ajax('get','/1.json',{
	success:()=>{}.fail:()=>{}
})
Copy the code

The problem with callbacks

  1. Not standard enough, the name is all over the place
  2. The promise chain calls solve the problem of callback hell, where we have nested asynchronous tasks layer upon layer within asynchronous tasks, resulting in code bloat.
  3. Error handling is hard to come by
			getUser((user) => {
				getGroups(user, (groups) => {
					groups.forEach((g) => {
						g.filter((x) => x.ownerId === user.Id).forEach((x) =>
							console.log(x)
						)
					})
				})
			})
Copy the code

Promise

The Promise object is created by the keyword new and its constructor. The constructor takes a function called “executor Function” as its argument. This “processor function” takes two functions, resolve and reject, as its arguments. The resolve function is called when the asynchronous task completes successfully and the result value is returned. The Reject function is called when the asynchronous task fails and returns the cause of the failure (usually an error object).

return new Promsie((resolve,reject)=>{... })Copy the code

The instance

Let myFirstPromise = new Promise(function(resolve, reject){resolve(...); Reject (...) is called when asynchronous code fails. // In this case, we use setTimeout(...) SetTimeout (function(){resolve(" success! ); // The code works fine! }, 250); }); Myfirstpromise.then (function(successMessage){resolve(...) // The successMessage argument doesn't have to be a string, but console.log("Yay! " + successMessage); });Copy the code
  • return new Promise((resolve,rejec)=>{... })
  • Called if the task succeedsresolve(result)
  • Called if the task failsreject(error)
  • resolveandrejectThe successful and failed functions are called again
  • use.then(success, fail)Pass in the success and failure functions
ajax = (method, url, options) => { return new Promise((resolve, reject) => { const { success, fail } = options const request27 = newXMLHttpRequest() request.open(method, Url) request. The onreadystatechange = () = > {the if (request. ReadyState = = = 4) {/ / success is invoked the resolve, Reject if (request. Status < 400) {resolve. Call (null, reject) request.response) } else if (request.status >= 400) { reject.call(null, request) } } } request.send() }) }Copy the code

But encapsulated JAXA can’t POST; Cannot add a status code

What do you know about Promise?

  • Promise wasn’t invented on the front end

  • Promise is a unified solution to asynchronous problems in front end

  • Window. Promise is a global function that can be used to construct Promise objects

  • Construct a Promise object using return New Promise((resolve, reject)=> {})

  • The constructed Promise object contains a.then() function property

. Then () with the catch ()

.then()

  • The then method provides a callback function that you can customize. If a non-function is passed, the current THEN method is ignored.
  • The callback takes the value returned from the previous THEN as the parameter value for the current THEN method to call.
  • The then method needs to return a new value for the next THEN call (undefined is used by default if there is no return value).
  • Each THEN may only use the return value of the previous THEN.

.catch()

If an exception is thrown when the resolve callback (the first argument in then above) is executed, the js will not be stuck, but instead will be thrown into the catch method.

This means that when an error occurs in a function, JS does not stop running, but passes the error to.catch(). Then proceed with the interface callback.

function getNumber() { var p = new Promise(function (resolve, Function () {var num = math.ceil (math.random () * 10) {if (num <= 5) { Resolve (num)} else {reject(num)}}, 1000)}) return p} getNumber(). Then ((data) => {console.log(" successful ") console.log(data)}). Catch ((data) => {console.log(" successful ") console.log(data)}). Console.log (" failed, error passed, continue ") console.log(data)}). Then (() => {console.log(" bypass, continue ")})Copy the code

Thus, the biggest benefit of promises is a clear separation of the code that executes and the code that processes the results in an asynchronously executed process.

jQuery.ajax

Jquery. ajax Chinese documentation

type

Type: String

Request type (“POST” or “GET”), default is “GET”. Note: Other HTTP request methods, such as PUT and DELETE, are also available, but only supported by some browsers.

url

Type: String

Address from which to send the request (default: current page address).

username

Type: String

The name of the user responding to an HTTP access authentication request

Var JQXHR = $.ajax("example.php").done(function() {alert("success"); }) .fail(function() { alert("error"); }) .always(function() { alert("complete"); }); // perform other work here ... Jqxhr.always (function() {alert("second complete"); });Copy the code

axios

Axios Chinese document

Axios is a Promise-based HTTP library that can be used in browsers and Node.js.

Performing a GET request

// create the request axios.get('/user? ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); Get ('/user', {params: {ID: 12345}}). Then (function (response) {console.log(response); }) .catch(function (error) { console.log(error); });Copy the code

Performing a POST request

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
Copy the code

Execute multiple concurrent requests

function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]).then(axios.spread(function (acct, perms) {// Both requests are now executed}));Copy the code

Source: Hungry Man Valley

This article is the original article, the copyright belongs to myself and hunrengu, must indicate the source of reprint