当前位置:网站首页>Async function ------ ES6

Async function ------ ES6

2022-04-23 20:28:00 Different 213

async function

ECMAScript 2017 The specification introduces async function , The main purpose of this function is to simplify the use Promises, Asynchronous call operation , And to a group Promises Do something . just as Promises Similar to structured callbacks ,async / await Similar to a combination generator and Promises.

The sample code is as follows :

function resolveAfter2Seconds() {
    
    return new Promise(resolve =>{
    
        setTimeout(()=>{
    
            resolve('resolved');
        },2000);
    });
}
/*// promise The way  let promise = resolveAfter2Seconds(); promise.then((value)=>{ console.log(value); });*/

// async Function mode 
async function asyncCall() {
    
    console.log('calling');
    var result = await resolveAfter2Seconds();
    console.log(result);//resolved
}
asyncCall();

One 、async The syntax structure of a function

(1) Asynchronous function declaration

Asynchronous function declarations are used to define a return Promise Object's asynchronous function . Asynchronous functions are functions that are executed asynchronously through an event loop , It will pass through an implicit Promise Return the result . But if the code uses asynchronous functions , Its syntax and structure will be more like standard synchronization functions .

async function name([param[,param[,...param]]]){
    statements}
  • name : Represents the function name .
  • param : The name of the parameter to be passed to the function .
  • statements : Represents a function body statement .

(2) Asynchronous function expression

Asynchronous function expressions are used to define asynchronous functions in expressions .

let name = async function([param1[,param2[,...parmaN]]]){
    statements}
  • name : Represents the function name .
  • param : The name of the parameter to be passed to the function .
  • statements : Represents a function body statement .

An asynchronous function expression is very similar to an asynchronous function statement , The grammar is basically the same . The main difference between them is that asynchronous function expressions can omit the function name to create an anonymous function .


return Promise object

async The function returns a Promise object .async Internal function return The value returned by the statement , It's going to be then Method callback function parameters .

// async  The function returns promise object 
async function myAsync() {
    
    return 'hello world';
}
let promise = myAsync();

promise.then((value) => {
    
    console.log(value);//hello world
})

Two 、await expression

await The expression is used to wait for a Promise object , It can only be used in asynchronous functions .

[return_value] = await expression
  • expression : One Promise Object or any value to wait .
  • return_value : return Promise The result of object processing . If it's not Promise object , Returns the value itself .
function createPromise() {
    
    return new Promise((resolve, reject) => {
    
        setTimeout(()=>{
    
            resolve(' The execution is successful ');
        });
    });
}

async function myAsync() {
    
    console.log(' The current asynchronous function has been called ');
    var result = await createPromise();
    console.log('Promise The result of the execution of the object :' + result)
}
myAsync();

Error handling

To prevent mistakes , Place it in try_catch In the sentence .

function createPromise() {
    
    return new Promise((resolve, reject) => {
    
        setTimeout(()=>{
    
            reject(' Execution failed ');
        });
    });
}

async function myAsync() {
    
    console.log(' The current asynchronous function has been called ');
    try{
    
        var result = await createPromise();
    }catch (e) {
    
        console.log('Promise The result of the execution of the object :' + e)
    }
}
myAsync();

Promise Object executes a set of Promise object

let promise1 = new Promise((resolve,reject)=>{
    
    setTimeout(()=>{
    
        resolve('one');
    },100);
});
let promise2 = new Promise((resolve,reject)=>{
    
    setTimeout(()=>{
    
        resolve('two');
    },200);
});
let promise3 = new Promise((resolve,reject)=>{
    
    setTimeout(()=>{
    
        resolve('three');
    },300);
});
async function myAsync() {
    
    let result1 = await promise3;
    console.log(result1);
    let result2 = await promise2;
    console.log(result2);
    let result3 = await promise1;
    console.log(result3);
}
myAsync();

3、 ... and 、 matters needing attention

  • try … catch sentence

    await After the order Promise object , The result of the run might be rejected, So it's better to await The expression is placed in try…catch Block of code .

  • Multiple await Asynchronous operation after expression , If there is no secondary relationship , It's better to let them trigger at the same time .

  • await Restrictions on expressions

    await Expressions can only be used in async Function , If it is used in ordinary functions , You're going to report a mistake .

版权声明
本文为[Different 213]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210550451095.html