Simple understanding of JavaScript async / await

What is the Async / Await?

  • async function: Function Generator is syntactic sugar
  • 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 / await the Promise, is non-blocking
  • Promise async function returns the object may await a command as a parameter

Second, grammar

1, return Promise objects

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"


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

the async function F () {
     the throw  new new Error ( ' wrong ' ); 
} 

F () the then (. 
    V => the console.log (V), 
    E => the console.log (E) 
) 
// Error: the error


2, the object state change Promise

Only asynchronous internal functions of async operation executed, will then execute the method specified callback function.

async function getTitle(url) {
    let response = await fetch(url);
    let html = await response.text();
    return html.match(/<title>([\s\S]+)<\/title>/i)[1];
}
getTitle('https://tc39.github.io/ecma262/').then(console.log)
// "ECMAScript 2017 Language Specification"

3, await command

Normally, await a command followed Promise object. If not, it will be turned into an object immediately resolve the Promise.

Promise await following the command if an object becomes a reject state, reject the catch process parameters will be received by the callback function.

As long as await a statement following the Promise into a reject, then the whole async function will interrupt execution

the async function F () {
     the await Promise.reject ( ' wrong ' );
     the await Promise.resolve ( ' Hello World ' ); // not executed 
}


Sometimes, we hope that even if an asynchronous operation failed before, and do not break the back of the asynchronous operation. Then you can put the first await a try ... catch structure inside, so regardless of whether the asynchronous operation is successful, the second will await execution.

async function f() {
    try {
        await Promise.reject('出错了');
    } catch(e) {
    }
    return await Promise.resolve('hello world');
}

f()
.then(v => console.log(v))
// hello world


Another method is to await Promise objects behind a catch talk method, processing errors may occur in front.

async function f() {
    await Promise.reject('出错了')
    .catch(e => console.log(e));
    return await Promise.resolve('hello world');
}

f()
.then(v => console.log(v))
// 出错了
// hello world


4, error handling

If the latter error await asynchronous operation, then the object is equivalent to the async Promise function returns the reject.

A method of preventing an error, which was placed into the try ... catch block.

the async function F () {
     the try {
         the await  new new Promise (function (Resolve, Reject) {
             the throw  new new Error ( ' wrong ' ); 
        }); 
    } the catch (E) { 
    } 
    return  the await ( ' Hello World ' ); 
} 
if there are more await commands can be unified on the try ... catch structure. 

the async function main () {
     the try {
         const val1 is = the await firstStep ();
         const val2 = the await secondStep(val1);
        const val3 = await thirdStep(val1, val2);
        console.log('Final: ', val3);
    }
    catch (err) {
        console.error(err);
    }
}

to sum up

Before the function  async key has two functions:

  1. Always return promise.
  2. Allowing wherein await.

In the await keyword before the promise, the promise JavaScript waiting to be processed, then:

  1. If there is error, an exception is thrown, just like in that place called the same throw error.
  2. Otherwise, the return value, we can assign a value to it.

 

Guess you like

Origin www.cnblogs.com/Mr-Tao/p/11108592.html