What is asynchronous? What is synchronization? 🙉

Synchronous:

Only one thread is blocked at a time

Simply put, it means completing one task after another. As long as one is not finished the others are blocked

Asynchronous:

Instead of blocking the current thread to wait for processing to complete, you allow subsequent operations until another thread has finished processing and notifying that thread with a callback.

In simple terms, tasks are carried out simultaneously and may need to wait for other tasks to complete before proceeding to the current task.

Why do JS need to be asynchronous? 🙉

Js is single-threaded, so if one task takes a long time, then the rest of the code is blocked.

The history of asynchronous programming in Js 👏

In fact, the purpose of asynchronous programming development is to coding happily: synchronous writing asynchronous

1. Callback function:

Callback function: a function that triggers the execution of an asynchronous operation. The format is similar to the following:

$.get("http://xxx.xxxx.com/api",callback);
Copy the code

Advantages:

  • simple
  • Conforms to traditional JS

Disadvantages:

  • If: we need to request A to get the student ID, request B to get the student score, and then request the student score to get the ranking (not A very good example but about the same idea).
fetch({
    url: "/student",
    data:1,
    success: function (id) {
        fetch({
            url: "/score",
            data:id,
            success: function (score) {
                fetch({
                    url: "/rank",
                    data:score,
                    success: function (rank) {
                        console.log(rank)
                    }
                })
            }
        })
    }
})
Copy the code
  • Callback nesting can make code difficult to maintain
  • And it’s not easy to uniformly handle errors (no try catch)

2. Promise:

Promises solve the problem of callback hell to some extent. Promises were first proposed and implemented by the community, and ES6 has written them into the language standard, unifying usage, and providing Promise objects natively. A Promise object is simply a container that holds the result of some event (usually an asynchronous operation) that will end in the future. Syntactically, a Promise is an object from which to get messages for asynchronous operations. Promise provides a uniform API, and all kinds of asynchronous operations can be handled in the same way.

fetch(1).then(id=> {
    return fetch(id);
}).then(score => {
    return fetch(score);
}).then(rank=> {
    console.log(rank)
}).catch(reason => {
    console.log(reason);
});
Copy the code

Advantages:

  • Once the state changes, it never changes again, and you can get this result at any time
  • Asynchronous operations can be expressed as a flow of synchronous operations, avoiding layers of nested callback functions

Disadvantages:

  • Unable to cancel Promise
  • When you are in a pending state, you cannot tell what stage you are currently in
  • Errors cannot be try caught

3. Generator

The Generator function is an asynchronous programming solution provided by ES6. The Generator function is a encapsulated asynchronous task, or a container for asynchronous tasks. Where asynchronous operations need to be paused, use the yield statement. Split the function into several parts and call next once to continue execution. The return result is an iterator that has a next method.

function my_co (it) {
    return new Promise((resolve, reject) => {
        function next(data) {
            let {value, done} = it.next(data);
            if(!done) {
                value.then(val => {
                    next(val);
                }, reject);
            }else{
                resolve(value);
            }
            
        }
        next();
    });
}

function *getData() {
    let res=yield fetch('/student', () = > {});let res1=yield fetch('/score',res1,()=>{});
    let res2=yield fetch('/rank',res2,()=>{});
    return res2
}
let it=getData()
let id=it.next(it)
let score=it.next(id)
let rank=it.next(score)
my_co(getData()).then(data => {
    console.log(data);
});
Copy the code

Special note: It may seem that the asynchronous writing of generator is not commonly used in our daily business, but in fact it has an important use in the development of some libraries. Right! That’s redux-saga and think about it and the way asynchronous programming has so much control that you can stop it if you want!

4. Aync await

Async-await is a syntactic sugar, which is implemented by wrapping Generator functions and auto-executor (CO) in a function. Async is equivalent to wrapping its function return value in promise.resolve (). Await is equivalent to the syntactic sugar of generator and promise, equivalent to yield, but synchronous code outside of it can automatically execute 🔔 or promise.all if there are no dependencies

// As in the above examplefunction fetchData(api) {
      let result
      let url = 'http://localhost:3000'
      fetch(url + api, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      })
        .then((res) => {
          return res.json()
        })
        .then((json) => {
          console.log(json)
          result=json
        })
       return result
}
async function getData() {let id=await fetchData('/student')
    let score=await fetchData('/score')
    let rank=await fetchData('/rank')}Copy the code

Advantages:

  • The code is clear,
  • Instead of writing as many “then” s as Promise,
  • Can handle callback hell
  • And errors can betry catch.
async function main() {
  try {
    const val1 = await firstStep();
    const val2 = await secondStep(val1);
    const val3 = await thirdStep(val1, val2);

    console.log('Final: ', val3); } catch (err) { console.error(err); }}Copy the code

🌰 Give it a try:

The git address contains examples of four different ways of asynchronous programming. You are welcome to try 👀

  1. How does JS implement asynchronous execution? Execution stack: The execution stack can be thought of as a stack structure for storing function calls, following a first-in, last-out pattern. When you execute JS, you put functions on the execution stack. Asynchrony is suspended and placed in the task queue. EventLoop: When the stack is empty, EventLoop puts the code to be executed from the queue into the stack. \
  2. Is WebWorker truly multithreaded? See [WebWorker, this time it will!]