Why asynchrony

Js is a language born for the browser. Now, JS is not only run on the browser, but also run on the server, like Node. Js is originally designed to be single-threaded, which means that it will execute line by line and wait for the above code to finish executing. In other words, it can only do certain things at a certain time and block the execution of other code.

Common asynchrony such as network request, file reading, etc.

Asynchronous solution

Knowing why asynchrony occurs in javascript, what can we do about it? How to write engineering code for everyday work? Several solutions have emerged in the evolution of javascript.

callback

In general web request we don’t know what time the server returns a result, in this process of waiting, we can’t let the page has been caton or operating state, this will give the user a bad experience feeling, when we need on the server and returns the corresponding operation or data update. The callback function becomes the first solution to asynchrony, as follows:

$.ajax({

    “url”: “”,

    success: function(data){

// The function returns the operation or data update required for success

    },

    error: function(err){

// The function returns an action or prompt for failure

   }

})

This is a familiar operation in JQ. When we request the server, the server will return a result regardless of success or failure. Success and error functions are callback functions, and we can perform corresponding operations or prompt regardless of success or failure. It does not affect the user’s ability to perform other operations (unless the user does not want to perform the operation and must wait for the operation to complete). When the server returns data, we can receive it through callback, and then we can perform the corresponding operation.

Promise

In callback, if the current network request needs to depend on a previous network request, we risk falling into callback hell,

As shown in figure:

Promise solved this problem for us. Promises are standardized in ES6 and supported directly by browsers. Promises stand for promise, meaning that they will return a result whether the state succeeds or fails in the future.

Promise has three states:

Pending;

This is a pity.

Have rejected;


let test = new promise(resolve,reject){

      if(success){

         resolve();

      }else{

        reject();

      }

}

test()

.then(res => {

// Returns the function on success

})

.catch(err => {

// Returns the function on failure

})


Generator

We wanted to write asynchronous code in a synchronous manner, so that the logic would be clear and the code would be concise. In order to achieve this goal, we evolved the generator scheme.

function * add(x){

   yield  x + 50;

   yield x + 100;

   return x + 150;

}

let  test = add(5);

test.next(); //done: true , value: 55

test.next(); //done: true , value: 105

test.next(); //done: true , value: 155

As above, genertor is not much different from normal functions, function is followed by an *,

First, we define a test = add(5), the function is not executed, just a Genertor object is generated, the function is paused, only when.next() is executed, the pause state is activated, the internal code is executed, the first yield is returned, and remember the context, pause, Surrender control, execute again, find the second yield, and repeat the steps above

function* Fn(){

  var result = yield ajax(url);

  var result1 = yield ajax(url1);

}

let F = Fn();

var result = F.next();

result.value

.then(res => {

The cash-strapped ext ();

})

.catch(err => {

})

Encapsulate an Ajax asynchrony, define a Genertor object, perform the request to surrender control, and perform the second Ajax request based on the returned result


asnyc/await

ES7’s ASNYC /await claims to be the ultimate solution to asynchrony, letting us write asynchronous code synchronously so it looks cleaner and more logical.

For example, wechat applet annoyingly asynchronous:

const Login = data => { 

  return new Promise( (resolve, reject) => { 

    wx.login({ 

      success: res => { 

         resolve(res);

       }, 

       fail: err => {  

          reject(err); 

        } 

      }) 

   }) 

}

const getUserInfos = data => {

  return new Promise((resolve,reject){

    wx.getUserInfo({

      success: res => { 

       resolve(res);

      },

     fail: err => {

       reject(err);

     } 

    })

  })

}

const sendCode = data = > {

  return new Promise((resolve,reject){

     wx.request({

       url: ”,

       success: res=> {

           resolve(res);

       },

       fail: err => {

          reject(err);

       }

     })

  })

}

These are the functions that encapsulate the wechat login process to get code userInfo and send Ajax requests.

then

asycn function getLogin(){

 try {

  let result_login = await Login();

  let result_userInfo = await getUserInfos();

  result_userInfo[‘code’] = result_login[‘code’];

  let result_sendCode = await sendCode(result_userInfo );

  return result_sendCode;

 }catch(err){

 console.log(err);

}

}

getLogin()

.then(res => {

})

.catch(err => {

}

Async is written similarly to Genertor, has better semantics, and returns promises