A, async
Async keyword, which indicates that an asynchronous operation may occur within a function. Such a function always returns a Promise, as follows:
- Resolve (undefined); resolve(undefined);
- Resolve (data); return promise.resolve (data);
- Return Promise, you get the Promise object itself
async function helloAsync(){ return "helloAsync"; } helloAsync().then(v=>{ console.log(v); //"helloAsync" })Copy the code
Second, await
The await keyword cannot be used alone as it needs to be used in async methods. Await literally means’ to wait ‘, so what is it waiting for? If it waits for something other than a Promise object, the result of the await expression operation is what it waits for. If it waits for a Promise object, await is busy and blocks the following code, waiting for the Promise object resolve, and then getting the value of resolve as the result of the await expression.
We know that Promise objects have two states, resolved, and rejected, so let’s see what happens if the Promise object becomes Rejected.
function testAwait(){ return Promise.reject("error"); } async function helloAsync(){ await testAwait(); console.log("helloAsync"); } helloAsync().then(v=>{console.log(v); }).catch(e=>{ console.log(e); //"error" });Copy the code
From the execution result, the return reject state is caught by the outer catch, and subsequent executions are terminated.
But in some cases, you want to continue execution after an error, not interrupt. In this case tcy… Catch Catches an exception inside a function.
function testAwait(){ return Promise.reject("error"); } async function helloAsync(){ try{ await testAwait(); }catch(e){ console.log("this error:"+e)//this error:error } console.log("helloAsync"); //helloAsync } helloAsync().then(v=>{ }).catch(e=>{ console.log(e); // No print});Copy the code
The exception is the try… After the catch, the following code continues without interruption.