es6 learning 4: async and await

async

asyncThe function returns a Promise object that can be used thento add callback method. When the function is executed, the event awaitwill return to the first, until the asynchronous operation is complete, followed by execution statement after the function in vivo.

function setNumAdd(n) {
            return new Promise((resolve,reject) =>{
                setTimeout( ()=>{
                    n +=1;
                    resolve(n)
                },1000)
            })
        }

        function setNumSub(n) {
            return new Promise((resolve,reject) =>{
                setTimeout( ()=>{
                    n -=1;
                    resolve(n)
                },1000)
            })
        }

        async function d(n) {
            const w1 = await setNumAdd(n);
            const w2 = await setNumSub(n);
            return w1+w2
        }
        d(10).then( v=>{
            console.log(v)  //10
        })

 

asyncThe function returns a Promise object. asyncInternal function returnvalue returned by the statement, will be the thenparameters of the method callback function.

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

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

 

asyncInternal functions throw an error will result Promise returned object becomes the rejectstate. Error object is thrown catchmethod callback function received.

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

f().then(
  v => console.log(v),
  e => console.log(e)
)

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

 

await

Normally, awaita command is followed by a Promise object, and returns the result of the object. If the object is not Promise, directly returns the corresponding value.

the async function F () {
   // equivalent 
  // return 123; 
  return the await 123 ;
}

f().then(v => console.log(v))
// 123

 

Any awaitstatement following the Promise object becomes rejecta state, then the whole asyncfunction will interrupt execution.

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

In the above code, the second awaitstatement is not executed, because the first awaitstatement into a state reject.

Sometimes, we hope that even if an asynchronous operation failed before, and do not break the back of the asynchronous operation. Then you can be the first awaitplace try...catchinside the structure, so that regardless of the asynchronous operation is successful, the second awaitwill be executed.

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

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

Another method is awaitbehind an object talk Promise a catchmethod, error processing may occur in front of

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

f()
.then (V => the console.log (V))
 // wrong 
// Hello World 
Error Handling

 

 

If there are multiple awaitcommands can be placed in a unified try...catchstructure.

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);
  }
}

 

let foo = await getFoo();
let bar = await getBar();

Multiple awaitcommand asynchronous operation later, if there is no secondary relationship, it is best to let them triggered simultaneously.

The above code, getFooand getBartwo separate asynchronous operations (i.e. not mutually dependent), is written as secondary relationship. This is more time-consuming, because onlygetFoo

After completion, it will be implemented getBar, so that they can simultaneously trigger.

// 写法一
let [foo, bar] = await Promise.all([getFoo(), getBar()]);

// writing two 
the let fooPromise = getFoo ();
let barPromise = getBar();
let foo = await fooPromise;
let bar = await barPromise;

 

Guess you like

Origin www.cnblogs.com/yangjie-space/p/11616591.html