ES6 new features Summary and Introduction - Asynchronous Programming

A, Generator

(A) the basic concept

Syntactically, Generator function is a state machine, a plurality of internal state of the package. Generator function returns an execution visitor object, that is, in addition to a function Generator state machine, or a visitor object generating function. Returning visitor object, may in turn through each state inside Generator function.

Formally, Generator function is a normal function, but there are two features. First, there is an asterisk between the function key and the function name; Second, the functions that use yield expression that defines the different internal states.

function* helloWorldGenerator() {
  yield 'hello';
  yield 'world';
  return 'ending';
}

var hw = helloWorldGenerator();
复制代码

The above code defines a function Generator helloWorldGenerator, has within it two expressions yield (Hello and world), i.e., the function has three states: hello, world and return statement (end of the execution).

Generator function calls the method with normal function, but also after the function name with a pair of parentheses. The difference is that, after calling Generator function, which is not performed, nor is the function is to return the result, but a pointer to the object's internal state, i.e. traverse the object (Iterator Object).

Next, you must call the next method traversing the object so that the pointer moves to the next state. That is, each call to the next method, internal pointer from one place to stop the function of the head or the execution, until the next yield expression (or return statement) so far. In other words, the function is piecewise Generator performed, the yield marker expression is suspended, and the next method can resume execution.

(Ii) yield

Because Generator function returns the visitor object, that's only traverse to the next internal state next method invocation, so in fact provides a way to suspend execution of the function. yield expression is a pause sign.

(C) Generator.prototype.next ()

The method of operating logic next visitor object as follows.

  1. Encounter yield expression, you suspend the operation of the back, and immediately after the yield value of the expression of the latter, as the value of the returned object property values.
  2. The next time you call the next method, and then continues down until the next yield expression.
  3. If you no longer meet the new yield expression, it has been run to the end of the function, until the return statement, and the return value of the expression behind the statement, as the value of the returned object property values.
  4. If the function does not return statement, then the value returned by the object attribute is undefined.

(四)Generator.prototype.throw()

Generator function object to traverse returned, there is a throw method can throw error function in vitro, and then trapped in the body of the function Generator.

var g = function* () {
  try {
    yield;
  } catch (e) {
    console.log('内部捕获', e);
  }
};

var i = g();
i.next();

try {
  i.throw('a');
  i.throw('b');
} catch (e) {
  console.log('外部捕获', e);
}
// 内部捕获 a
// 外部捕获 b
复制代码

The above code, the object traversing i throw two consecutive errors. Generator is captured first error function in vivo catch statement. i second throw an error, since the interior of the catch statement Generator function has been performed, and will not catch the error, so the error was thrown Generator function body, the captured vitro function catch statement.

(五)Generator.prototype.return()

Generator function returns the visitor object, there is a return method, can be returned to a predetermined value, and the end of traversal Generator function.

function* gen() {
  yield 1;
  yield 2;
  yield 3;
}

var g = gen();

g.next()        // { value: 1, done: false }
g.return('foo') // { value: "foo", done: true }
g.next()        // { value: undefined, done: true }
复制代码

If the return call method, the parameter is not available, value property is returned value is undefined.

If the internal Generator function has try ... finally block and try block is executed, then the method will return to the deferred finally block executing the re-execution.

二、Promise

(A) state Promise

Promise asynchronous operation has three states: pending (in progress), fulfilled (been successful) and rejected (failed). In addition to the results of an asynchronous operation, no other operations can change that state.

Promise only objects: from pending changes to become fulfilled and rejected the pending state changes. As long as fulfilled in and rejected, the state will not have changed that is resolved (finalized).

(二)Promise.prototype.then()

The method then receives the first parameter as a function of two parameters, then the method is resolved state of the callback function, the second parameter (optional) is the callback rejected state. Both functions will be only one is called.

const promise = new Promise(function(resolve, reject) {
  if (/* 异步操作成功 */){
    resolve(value)
  } else {
    reject(error)
  }
})
promise.then(function(value) {
  // success
}, function(error) {
  // failure
})
复制代码

(三)Promise.prototype.catch()

Promise.prototype.catch is .then (null, rejection) or .then (undefined, rejection) alias, when a callback function for specifying an error occurs. In general, do not define the Reject state which then callback method (i.e., then the second parameter), always use a catch method.

// bad
promise
  .then(function(data) {
    // success
  }, function(err) {
    // error
  });

// good
promise
  .then(function(data) { //cb
    // success
  })
  .catch(function(err) {
    // error
  });
复制代码

(四)Promise.prototype.finally()

finally, regardless of the method used to target Promise final state, the operation will be performed specified.

promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···})
复制代码

In the above code, regardless of the final status Promise, then after completion of execution or catch specified callback function that executes the method finally specified callback function.

(五)Promise.all()

Promise.all method for multiple instances Promise, Promise packaged into a new instance.

const p = Promise.all([p1, p2, p3])
复制代码

The above code, Promise.all method takes an array as a parameter, p1, p2, p3 are Promise, p is determined by the state of p1, p2, p3, is divided into two cases.

  1. Only p1, p2, p3 have become Fulfilled state, the state will become a p Fulfilled, this time p1, p2, p3 composed of an array of the return value, p is passed to the callback function.
  2. Among long p1, p2, p3 is a Rejected, the state becomes the p Rejected, return values ​​at this time is the first instance of the reject, is passed to the callback function p.

(六)Promise.race()

The method also Promise.race multiple instances Promise, Promise packaged into a new instance.

const p = Promise.race([p1, p2, p3])
复制代码

The above code, as long as one example among p1, p2, p3 lead changes state, the state will change with p. Promise to return the value of that instance of the first to change, it is passed to the callback function p.

(七)Promise.resolve()

Sometimes you need to turn existing objects Promise objects, Promise.resolve method to play this role.

  1. Parameter is an instance of Promise

    If the argument is Promise instance, then Promise.resolve will not do any modification, is returned unchanged this instance.

  2. Object parameter is a thenable

    Promise.resolve method converts the object into Promise object and then immediately execute method thenable object.

  3. Parameter is not an object then the method, or is simply not an object

    If the parameter is a primitive value or object does not then have a method, the method returns a new Promise.resolve Promise object status is resolved.

  4. No parameters

    Promise the object with no parameters Promise.resolve () method allows the call to directly return a resolved state.

(八)Promise.reject()

Promise.reject (reason) method also returns a new Promise instance, the instance state is rejected.

Three, async

(A) Basic Usage

async function returns a Promise objects can be added using the callback method then. When the function is executed, the event will be to go back to await until the asynchronous operation is complete, followed by execution statement after the function in vivo.

async function getStockPriceByName(name) {
  const symbol = await getStockSymbol(name)
  const stockPrice = await getStockPrice(symbol)
  return stockPrice
}

getStockPriceByName('goog').then(function (result) {
  console.log(result)
})
复制代码

(Ii) Object Returns Promise

async function returns a Promise object. Internal async function return value returned by the statement, will be the method parameters then the callback function.

async function f() {
  return 'hello world'
}

f().then(v => console.log(v))
// "hello world"
复制代码

In the above code, the internal function f return value of the command is returned, the method is then received by the callback function.

Internal async function throws an error will result Promise returned object becomes reject state. Error object is thrown callback method receives a catch.

async function f() {
  throw new Error('出错了')
}

f().then(
  v => console.log(v),
  e => console.log(e)
)
// Error: 出错了
复制代码

(C) await command

  1. Under normal circumstances, the await command followed by a Promise object, and returns the result of the object. If the object is not Promise, directly returns the corresponding value.
async function f() {
  // 等同于
  // return 123;
  return await 123;
}

f().then(v => console.log(v))
// 123
复制代码
  1. In other cases, await a command followed thenable object (i.e., the method then defines the object), it will await an object which is equivalent to Promise.

(Iv) Precautions

  1. Promise await command behind the object, the result may be Rejected operation, it is best to await a command on the try ... catch block.
// good
async function myFunction() {
  try {
    await somethingThatReturnsAPromise();
  } catch (err) {
    console.log(err);
  }
}

// bad
async function myFunction() {
  await somethingThatReturnsAPromise()
  .catch(function (err) {
    console.log(err)
  })
}
复制代码
  1. More await an asynchronous operation command back, if there is no secondary relationship, it is best to let them triggered simultaneously.
// good
let [foo, bar] = await Promise.all([getFoo(), getBar()]);

// bad
let fooPromise = getFoo();
let barPromise = getBar();
let foo = await fooPromise;
let bar = await barPromise;
复制代码
  1. await command can only be used in the async function, if used in an ordinary function will error.
  2. async function can keep running Stacker.

Reproduced in: https: //juejin.im/post/5cf87a4b518825789e031e82

Guess you like

Origin blog.csdn.net/weixin_34362875/article/details/91428694