A simple function is used to illustrate this

Synchronous code function calls

	function add (a, b) {
		let c = a + b
		return c
	}
// Call mode
    let c = add(1.2)
// Get a C, do something

Copy the code

Synchronous code, single thread with JS, executed from top to bottom

Asynchronous code – callback functions

function add (a, b, callback) {
	let c = a + b
	/ /... Omit intermediate code
	/ / call the callback
	callback(err, c)   
}
// Call mode
// The first argument to the callback function defaults to an error, and the second is the value returned by the calling function
demo(1.2.function( err, c ) {
	if (err) throw err
	// Get the returned c to do something
	// ...
	console.log(c)
})
Copy the code

When the add function is called, the incoming function is not executed synchronously. Instead, it waits for the call to be executed

Asynchronous function — Promise

function add (a, b) {
	return new Promise(resolve, reject ) {
		let c = a + b 
		resolve (c)  // reject(c)}}/ / call
demo(1.2).then(c= > {  // catch(() => {})
	// get the result c
	/ /... Do something
	console.log(c)
})
Copy the code
  1. Promise, effectively reducing the problem of callback hell
  2. Note the obvious difference between the way promise is called and the callback function
  3. Resolve corresponds to then, indicating the successful state. Reject indicates catch, indicating a failure
  4. As the amount of code increases, this promise approach becomes bloated, leading to async await sugar, which simplifies writing

Asynchronous code — async + await

async function add (a, b) {
	let c = a + b
	return c 
}
/ / call
let c = await add(1.2)
// Get a C, do something
Copy the code
  1. This writing method and the first synchronization code is exactly the same, but more than two keywords to modify, have to say that writing is very convenient
  2. Async means that the function returns a promise, in which the value returned by the return represents the value returned by resolce/reject (back to synchronous writing).
  3. Await can only be used in async modified functions to indicate that asynchronous code is being executed after waiting, simplifying the writing of then and catch in PROMsie

conclusion

From synchronization to callback,promise, and async+ await, the way of writing code changes from simple to complex and simple again, but the meaning of expression is completely different. It has to be said that the charm of program design is displayed vividly here.