Asynchronous programming is very important in JavaScript, but too much asynchronous programming also introduces the problem of nested callbacks.


What is a callback function?

ajax(url, () => {});Copy the code

The above code is a callback function. One function as an argument needs to rely on another function to perform the call.

But Callback functions have an Achilles’ heel: Callback hell.

What is callback hell?

let form = document.querySelector('form');
form.onsubmit = function (e) {
  var name = document.querySelector('input').value;
  $.ajax({
    url: "http://demo.com/submit".type:'POST',
    data: {name: name},
    success: function(res) {
        if (res.code === 2000) {
            var h1 = document.querySelector('h1').innerHTML; h1.innerHTML = res.data.name; }}}); }Copy the code

As such, the nesting of functions as parameters makes the code block look large, unclear, and unable to distinguish structural levels all at once, which is called “callback hell.”

The fundamental problems and drawbacks of callback hell:

  1. Nested functions are coupled and can be affected by changes
  2. Multiple nested functions make it difficult to handle errors
  3. The callback function state uses try… catch… Error caught, cannot return directly

How to solve callback hell?

The main reason is the coding habits of developers, which can be solved in the following ways:

  • Keep your code short and use named functions instead of anonymous ones

document.querySelector('form').onsubmit = onFormSubmit();

function onFormSubmit(e) {
  var name = document.querySelector('input').value;
  $.ajax({
    url: "http://demo.com/submit".type:'POST',
    data: {name: name},
    success: onSuccess(res)
  });
}

function onSuccess(res){
    if (res.code === 2000) {
        var h1 = document.querySelector('h1').innerHTML; h1.innerHTML = res.data.name; }}Copy the code

  • Modularization, split each independent function function, packaging, packaging into a separate JS file, through import import

// formHandler.js
module.exports.formSubmit = onFormSubmit;

function onFormSubmit(e) {
  var name = document.querySelector('input').value;
  $.ajax({
    url: "http://demo.com/submit".type:'POST',
    data: {name: name},
    success: onSuccess(res)
  });
}

function onSuccess(res){
    if (res.code === 2000) {
        var h1 = document.querySelector('h1').innerHTML;
        h1.innerHTML = res.data.name;
    }
}

// index.js
var formHandler = require('./formHandler');
document.querySelector('form').onsubmit = formHandler.formSubmit;Copy the code
  • Handle each error and code according to standard specifications
  • Promise/Gengenerator/Async Function

In addition to a callback function as common asynchronous processing, and promises, Generators, async is asynchronous processing

What are the features of promises?


  1. Pending
  2. Completed (Resolved)
  3. I have rejected your offer.

Once the state of this promise is changed, it cannot be changed again

When we construct a Promise, the code inside the constructor executes immediately

new Promise((resolve, reject) => {
  console.log('new Promise')
  resolve('success')
})
console.log('finish');

// new Promise
// finishCopy the code

What are the downsides of Promises?

There is no way to cancel the Promise, and the error needs to be caught with a callback function

What is the Promise chain? What is the difference between Promise constructor execution and THEN execution?

Promise

Chain calls are implemented, that is, each time then is called
Every Promise that comes back is a Promise
“And it’s a brand new Promise
And the reason is because the state is immutable. If you are in then
Return is used in
, then return
Is used by promise.reslove ().
packaging

Promise.resovle(1) .then(res => { console.log(res); / / 1return2; }). Then (res => {console.log(res); / / 2})Copy the code

Promise also solved the problem of hell callbacks:

/ / old ajax (url, () = > {/ / processing logic ajax (url1, () = > {/ / processing logic ajax (url2, () = > {/ / processing logic})})}) / / new ajax (url). Then (res = > {the console. The log (res);return ajax(url1);
    })
    .then(res => {
        console.log(res);
        return ajax(url2);
    })
    .then(res => console.log(res));
Copy the code

Async and await

Await synchronization only synchronizes within async functions and does not block execution of other external code. This is why await must be placed in async functions

Async is used to declare that a function is asynchronous and await is used to wait for an asynchronous method to complete.


To be continued…