Async and await are js solutions to asynchronous programming

Async function is used to declare an asynchronous function that returns a Promise await followed by a function that returns a Promise await and executes the function, await suspends the execution of async code, Using async and await until the Promise is finished makes the syntax and structure of asynchronous functions more like synchronous functionsCopy the code

Async grammar

async function f() { return 1; } function foo() {return promise.resolve (1)}Copy the code

Async returns a promise

The returned Promise object runs either resolve, reject, or if function returns a value, Async function f() {return 1; } f().then((res) => { console.log(res) // 1 })Copy the code

The value returned by the return statement inside the async function becomes an argument to the then method callback function

async function f() {
  return 'hello world';
}
f().then(v => console.log(v))     // "hello world"
Copy the code

Await the operator

"Await" is used to wait for a Promise object. It can only be used in asynchronous async functions. Await suspends async execution and waits for the Promise processing to complete. If the Promise async operation succeeds, the resolve callback argument is used as the await expression value to continue async. If the Promise async operation fails, Await will throw the exception cause of the Promise. Async will run synchronously until an await is encountered, Async function foo(){await 1} is equivalent to function foo(){return Promise.resolve(1).then(() => undefined) }Copy the code

Error handling (await only a result, how to catch an error when an error occurs asynchronously)

Async function myFunction() {try {await promise.reject ('1'); } catch (err) { console.log(err); } } myFunction(); Async function myFunction() {await promise.reject ('1'). Catch ((err) => {console.log(err); }); } myFunction(); / / 1Copy the code

The async function throws an error, which causes the returned Promise object to be reject. The thrown error object is received by the catch callback

Async function f() {throw new Error(' Error '); } f().then( v => console.log(v), e => console.log(e) )Copy the code

The state change of the Promise object returned by async

No state change will occur until all Promise objects following the internal await command are executed, or a return statement or an error is thrown. Only asynchronous operations inside async functions are completed. 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 (the console. The log) only function within the getTitle three operation is completed, will perform then method inside the console. The logCopy the code

If the Promise object after await goes reject, the reject argument is received by the catch callback

Async function f() {await promise.reject (' error '); } f().then(v => console.log(v)).catch(e => console.log(e))Copy the code

Any Promise object after await goes reject, and the whole async function breaks

Async function f() {await promise.reject (' error '); await Promise.resolve('hello world'); // do not execute}Copy the code

If an asynchronous operation following await fails, the Promise object returned by the async function is rejected

Async function f() {await new Promise(function (resolve, reject) {throw new Error(' Error '); }); } f().then(v => console.log(v)).catch(e => console.log(e)) f after execution, the Promise behind await will throw an error object, causing the catch callback to be called with the argument of the thrown error objectCopy the code

To prevent errors, use a try catch

Async function f() {try {await new Promise(function (resolve, reject) {throw new Error(' Error '); }); } catch(e) { } return await('hello world'); }Copy the code

If you have more than one await command, you can put it in a try catch

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); }}Copy the code

Considerations for using async and await

1. Await a Promise object from a try catch (rejected). 2. Asynchronous operations following multiple await commands, if there is no secondary relationship (independent of each other), it is better to have them both fire let foo = await getFoo(); let bar = await getBar(); Equivalent to let [foo, bar] = await promise.all ([getFoo(), getBar()]); 3.await command can only be used in async functions, if used in normal functions, an error will be reportedCopy the code

Difference between Async and Promise

Examples: On top of the DOM element, you deploy a series of animations that start when the first animation ends and then stop if one of the animations fails, Returns the return value of the last successfully executed animation using Promise function chainAnimationsPromise(ELEm, animations) {let ret = null; // let p = promise.resolve (); let p = promise.resolve (); // Create an empty Promise for(let anim of animations) {// Use the then method to add all animations p = p.chen (function(val) {ret = val; return anim(elem); }); } return p.catch(function(e) {return a Promise with an error trap}). Then (function() {return ret; }); } Promises are all apis for promises (then, catch, etc.), Async Async Function chainAnimationsAsync(elem, animations) {let ret = null; try { for(let anim of animations) { ret = await anim(elem); }} catch(e) {a return ret; } async function implementation is the most concise, the most semantic, almost no semantically irrelevant codeCopy the code

Example: Complete asynchronous operations sequentially (read a set of urls remotely in turn and output the results in the order they were read)

The Promise is written as follows: function logInOrder(urls) {const textPromises = urls.map(url => {// Remotely read all URLS return fetch(url).then(response => response.text()); }); textPromises.reduce((chain, TextPromise) => {// Return chain.then(() => textPromise).then(text => console.log(text)); }, Promise.resolve()); } Use the fetch method to fetch a set of urls remotely, each fetch operation returns a Promise object, put textPromises into an array, reduce processes each Promise object in turn, and then concatenate all Promise objects. Async function logInOrder(urls) {const textPromises = urls.map(async URL => {// read remote URL const concurrently  response = await fetch(url); return response.text(); }); For (const textPromise of textPromises) {// Output console.log(await textPromise) in order; }} map method's parameters is async function and concurrent execution, it is because only the async function is secondary, external are not affected Behind the for of the cycle for internal use await, thus realizes the output in sequenceCopy the code

conclusion

Async /await is a Promise based approach to asynchronous operations that is semantically more readable and easier to use