JS asynchronous solutions

  Foreword

    The first solution is asynchronous callbacks, such as ajax, callbacks events, setInterval / setTimeout callback. But the callback function callback hell of a problem;

    In order to solve the problem of callback hell, community Promise proposed solutions, ES6 be written into the language standard. Solve the problem of callback hell, but there Promise Promise to some extent, on some issues, such as the error can not be try catch, and the use of chained calls Promise, in fact, does not solve the problem fundamentally callback hell, just for a writing.

    Generator function introduced ES6, Generator is an asynchronous programming solution, Generator functions are implemented in the coroutine ES6, the biggest feature is the implementation of the right hand function, the function can be seen that a container Generator asynchronous tasks, to pause the places are marked with a yield statement. However Generator to use more complex.

    ES7 also proposed a new asynchronous solution: async / await, async is syntactic sugar Generator function, async / await makes asynchronous code looks like synchronization code, asynchronous programming development goal is to make asynchronous logic code looks like the same synchronization .

  Synchronous and asynchronous

  Reference article on the concept of synchronous and asynchronous, here Ruan Yifeng teacher. Some of these are examples of asynchronous solutions, such as the "four ways js asynchronous programming" , "Asynchronous Operations Overview" .

   Asynchronous Solutions

  Callback

. 1  // Node read the file 
2 fs.readFile ( 'URL', 'UTF-. 8', function (ERR, Data) {
 . 3    // code 
. 4 });

   Scenarios used are: ajax request, the event callback function, Node API, timers.

   Pros: Simple. Cons: asynchronous callback nested lead to code difficult to maintain, and inconvenient unified processing errors, can not   , and there is a callback hell problem.try,catch

// Callback Hell problems A text to read, then read the text in accordance with B A C and then read the contents of the B .. Example 
fs.readFile ( 'A', 'UTF-. 8', function (ERR , Data) { 
    fs.readFile ( 'B', 'UTF-. 8', function (ERR, Data) { 
        fs.readFile ( 'C', 'UTF-. 8', function (ERR, Data) { 
            fs.readFile ( 'D', 'UTF-. 8', function (ERR, Data) {
                 // code 
            }); 
        }); 
    }); 
});

    Promise

  Promise to some extent, solve the problem of callback hell, Promise was first proposed and implemented, ES6 be written into the standard language, unified usage, native objects provided by the Community Promise. "ECMAScript 6 Getting Started"

  Let's look at how Promise is to solve the problem of callback hell.

function read(url) {
  return new Promise((resolve, reject) => {
       fs.readFile(url, 'utf-8', function(err, data) {
           if (err)  reject(err);
           resolve(data);
       });
  });
}
read('A').then(data => {
    return read('B');
}).then(data => {
    return read('C');
}).then(data => {
    return read('D');
}).catch(err => {
console.log(err);
});

    Promise advantages: 1. Once the status change, will not change, at any time this result can be obtained. 2. The process may be asynchronous operation to synchronous operation expressed, to avoid deeply nested callback

         Shortcoming promise: 1. You can not cancel Promise. 2. While in pending status, progress is currently no way of knowing where a stage. 3. The error can not be trycatch

         To give a prior Promise, reading the A, B, C three contents of the file are read successfully, and then outputs the final results of examples. It relies on a subscription model release

let pubsup = {
  arry: [],
  emit: function() {
    this.arry.forEach(fn => fn());
  },
  on: function(fn) {
     this.arry.push(fn);
  }
};
let data = [];
pubsub.on(() => {
  if (data.length == 3) {
    console.log(data);
  }
});
fs.readFile('A', 'utf-8', function(err, data) {
  data.push(data);
  pubsup.emit();
});
fs.readFile('B', 'utf-8', function(err, data) {
  data.push(data);
  pubsup.emit();
});
fs.readFile('C', 'utf-8', function(err, data) {
  data.push(data);
  pubsup.emit();
});

Incidentally Park spiritual practice which describes in simple terms nodejs get data asynchronously operating under different scenarios, very worth seeing.

Promise provides us with a   way for this demand, we can use   to achieve.Promise.allPromise.all

/ * * 
 * The packaged fs.readFile promise interfaces 
 * / 
function Read (URL) {
   return  new new Promise ((Resolve, Reject) => { 
    fs.readFile (URL, 'UTF-. 8', function (ERR, Data) {
        IF (ERR) Reject (ERR); 
       Resolve (Data); 
    }); 
  }); 
} 
/ * * 
 problems * Promise.all multiple asynchronous parallel execution can be realized, the same time to obtain the final result 
 * / 
Promise.all ( [ 
  Read (A), 
  Read (B), 
  Read (C) 
]) the then (Data. => { 
  the console.log (Data); 
}.) the catch (ERR => the console.log (ERR));

    Generator

        Generator function is an asynchronous programming solutions ES6 provided, the entire package is a function Generator asynchronous task, a container or asynchronous tasks. Asynchronous operations need to pause the place, are marked with the yield statement.

        Generator functions are typically used with Promise or yield. Generator function returns an iterator. For starters ES6 Ruan Yifeng under reference generator and the students do not understand the iterator

function * Generator () { 
  the let A = the yield 111 ; 
  the console.log (A); 
  the let B = the yield 222 ; 
  the console.log (B); 
  the let C = the yield 333 ; 
  the console.log (C); 
  the let D = the yield 444 ; 
  the console.log (D); 
} 
the let T = Generator ();
 // Next method can take a parameter which will be treated as a return value of the expression yield 
t.next (. 1); // first when the next call function, an invalid argument passed 
t.next (2); // output 2 
t.next (. 3); // . 3 
t.next (. 4); // . 4 
t.next (. 5); / / 5

Still more text readFile (A text to read, and then read in accordance with B A C According to re-read the text content B), for example, using Generator + co library to implement:

const fs = require('fs');
const co = require('co');
const bluebird = require('bluebird');
const readFile = bluebird.promiseify(fs.readFile);
function* read() {
  yield readFile('A', 'utf-8');
  yield readFile('B', 'utf-8');
  yield readFile('C', 'utf-8');
}
co(read()).then(data => {
  // code
}).catch(err => {
 // code
});

    await/async

      ES7 introduced async / await concept. async is actually a syntactic sugar, it is the realization of the Generator function and automatic actuator (co), packaged in a function.

      Advantage of async / await the code is clear, then do not write a lot like the Promise chain, it can deal with the callback hell. And the error can be try catch.

      Still more text readFile (A text to read, and then read in accordance with B A C According to re-read the text content B) as an example, using the async / await achieved:

const fs = require('fs');
const co = require('co');
const bluebird = require('bluebird');
const readFile = bluebird.promiseify(fs.readFile);
async function read() {
  await readFile('A', 'utf-8');
  await readFile('B', 'utf-8');
  await readFile('C', 'utf-8');
}
co(read()).then(data => {
  // code
}).catch(err => {
 // code
});

  We use async / await to achieve the same effect.

function read(url) {
  return new Promise((resolve, reject) => {
      fs.readFile(url, 'utf-8', function(err, data) {
          if (err) reject(err);
          resolve(data);
      })
  });
}
async function readAsync() {
  const data = await Promise.all([
      read(A),  
      read(B),
      read(C)
  ]);
  return data;
}
readSync().then(data => {
  console.log(data);
})

So the history of JS asynchronous development, can be considered from the callback -> promise -> generator -> async / await. async / await makes asynchronous code looks like the target synchronization code, asynchronous programming development is to make asynchronous logic code looks like the same synchronization

Guess you like

Origin www.cnblogs.com/cleaverlove/p/10962527.html