This is the 4th day of my participation in the August More Text Challenge

Don’t say a word, just get to work…

What is async function

  • It’s very simple, like the following 👇, before ordinary functionsasyncThe keyword is async function.
async function fn() {
    // Some of your actions
    await console.log('Write anything')}Copy the code

How, see this is not already ready silently of start despise 😒, this…

Don’t worry, let’s go on…

  • Async functions are syntactic sugar for Generator functions.
  • The same async method can be used to solve callback hell, and it’s written more like synchronous.
  • It has the following characteristics:
    1. Built-in actuators (as opposed to Generator functions)
    2. Better semantics
      • asyncIt means that there are asynchronous operations in the function,awaitIndicates that the following expression needs to wait for the result.
    3. Wider applicability
      • asyncFunction of theawaitThe command can be followed by a Promise object and a value of the original type (numeric, string, and Boolean, but will be automatically converted to an immediate Resolved Promise object).
    4. The return value is Promise
      • The async function returns a Promise object. This means that you can use the THEN method to specify what happens next.

usage

  • The async function returns a Promise object, and callbacks can be added using the then method.
  • When the function executes,Return "await" as soon as it encounters "await".Wait for the asynchronous operation to complete, then execute the following statement in the function body.

Seeing this, I believe you already know some basic things about async functions. As the saying goes, learn is to use, open dry…

// Function declaration
async function foo() {}

// Function expression
const foo = async function () {};

// Object method
let obj = { async foo(){}}; obj.foo().then(...)// Class method
class Storage {
  constructor() {
    this.cachePromise = caches.open('avatars');
  }

  async getAvatar(name) {
    const cache = await this.cachePromise;
    return cache.match(`/avatars/${name}.jpg`); }}const storage = new Storage();
storage.getAvatar('jake'). Then (...). ;// Arrow function
const foo = async() = > {};Copy the code

Return a Promise object

  • asyncThe function returns a Promise object.
  • asyncFunction of the internalreturnThe value returned by the statement becomesthenMethod to call the argument to the function.
  • asyncThe function throws an error internally that causes the returned Promise object to becomerejectState. The thrown error object will be removedcatchThe method callback function receives.

The state change of the Promise object

  • asyncThe Promise object returned by the function must wait until the internalawaitThe state change does not occur until the Promise object following the command is executed, unless encounteredreturnStatement or throw an error.
  • In other words:onlyasyncThe asynchronous operation inside the function is executed only after it has been executedthenMethod specifies the callback function.

Watch a 🌰 :

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"
Copy the code

Console. log will not be executed until the async function getTitle completes all three operations (fetching web pages, retrieving text, matching title)

Await orders

  • Under normal conditions:

    • awaitThe command is followed by a Promise object that returns the result of that object.
    • If it is not a Promise object, the corresponding value is returned.
  • Another case:

    • The await command is followed by a Thenable object (that is, the object that defines the then method), and await will equate it with a Promise object
  • Any Promise object after an await statement becomes reject, and the entire async function breaks.

async function f() {
  await Promise.reject('Wrong');
  await Promise.resolve('hello world'); // Will not be executed
}
Copy the code

At this point, if we still need to await it properly, we need to place the first await in the try… Catch structure.

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

f().then(val= > console.log(val))
Copy the code

So, is there another way to handle it? There has to be. A Promise object after await can be followed by a catch method to handle any previous errors that may occur.

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

f()
.then(v= > console.log(v))
/ / make a mistake
// hello world
Copy the code

Error handling

  • If an asynchronous operation following await fails, the Promise object returned by the async function is rejected.
  • In this case, try… The catch structure wraps the await statement.

Pay attention to the point

  • If multiple await commands are followed by asynchronous operations with no dependencies, it is best to let them all start at the same time. As follows:
/ / write one
let [foo, bar] = await Promise.all([getFoo(), getBar()]);

/ / write two
let fooPromise = getFoo();
let barPromise = getBar();
let foo = await fooPromise;
let bar = await barPromise;
Copy the code
  • Await can only be used in async functions.

  • Async functions can preserve the run stack.

Reference for this article: GETTING started with ES6

Relevant interview questions

async function async1(){
    console.log('async1 start')
    await async2()
    console.log('async1 end')}async function async2(){
    console.log('async2')}console.log('script start')
setTimeout(function(){
    console.log('setTimeout')},0)  
async1();
new Promise(function(resolve){
    console.log('promise1')
    resolve();
}).then(function(){
    console.log('promise2')})console.log('script end')
Copy the code

More complete here: 2021 front-end interview knowledge summary JS article

The end of the

Stop it! It’s over! It’s over!