async/await

  • Grammar is introduced
  • With Promise
  • Asynchronous nature
  • for… of

There are many async interview questions, for example

  • Async returns directly, what is it
  • Async returns the promise directly
  • Await without promise
  • Wait, we need to find a pattern

Grammar is introduced

Write asynchronously in a synchronous manner.

function loadImg(src) {
    const promise = new Promise((resolve, reject) = > {
        const img = document.createElement('img')
        img.onload = () = > {
            resolve(img)
        }
        img.onerror = () = > {
            reject(new Error('Image load failed${src}`))
        }
        img.src = src
    })
    return promise
}

async function loadImg1() {
    const src1 = 'http://www.imooc.com/static/img/index/logo_new.png'
    const img1 = await loadImg(src1)
    return img1
}

async function loadImg2() {
    const src2 = 'https://avatars3.githubusercontent.com/u/9583120'
    const img2 = await loadImg(src2)
    return img2
}

(async function () {
    // Note: await must be placed in async function otherwise an error will be reported
    try {
        // Load the first image
        const img1 = await loadImg1()
        console.log(img1)
        // Load the second image
        const img2 = await loadImg2()
        console.log(img2)
    } catch (ex) {
        console.error(ex)
    }
})()
Copy the code

With Promise

  • Async functions return Promise objects (if no Promise is returned in the function, it will be wrapped automatically)
async function fn2() {
    return new Promise(() = >{})}console.log( fn2() )

async function fn1() {
    return 100
}
console.log( fn1() ) // equivalent to promise.resolve (100)
Copy the code
  • Await followed by a Promise object: blocks subsequent code and waits for the state to become resolved before getting the result and continuing
  • Await followed by non-promise objects: will return directly
(async function () {
    const p1 = new Promise(() = > {})
    await p1
    console.log('p1') // Will not be executed}) () (async function () {
    const p2 = Promise.resolve(100)
    const res = await p2
    console.log(res) / / 100}) () (async function () {
    const res = await 100
    console.log(res) / / 100}) () (async function () {
    const p3 = Promise.reject('some err')
    const res = await p3
    console.log(res) // Will not be executed}) ()Copy the code
  • try… Catch Catches the Rejected state
(async function () {
    const p4 = Promise.reject('some err')
    try {
        const res = await p4
        console.log(res)
    } catch (ex) {
        console.error(ex)
    }
})()
Copy the code

To sum up:

  • Async encapsulation Promise
  • Await processing Promise success
  • try… The catch processing Promise failed

Asynchronous nature

Await is synchronous, but it is still an asynchronous call in nature.

async function async1 () {
  console.log('async1 start')
  await async2()
  console.log('async1 end') // This is the key step, which is put in callback and executed last
}

async function async2 () {
  console.log('async2')}console.log('script start')
async1()
console.log('script end')
Copy the code

That is, whenever an await is encountered, the following code is equivalent to being placed in a callback.

for… of

// Time the multiplication
function multi(num) {
    return new Promise((resolve) = > {
        setTimeout(() = > {
            resolve(num * num)
        }, 1000)})}// // uses forEach, which prints all results after 1s, i.e., the three values are computed together
// function test1 () {
// const nums = [1, 2, 3];
// nums.forEach(async x => {
// const res = await multi(x);
// console.log(res);
/ /})
// }
// test1();

/ / used for... "Of" allows calculations to be executed sequentially
async function test2 () {
    const nums = [1.2.3];
    for (let x of nums) {
        / / in the for... Inside the body of the "of" loop, await is evaluated sequentially
        const res = await multi(x)
        console.log(res)
    }
}
test2()
Copy the code

The async function executes and returns a Promise object

Await is equivalent to then of Promise

try… Catch catches exceptions instead of the catch of a Promise

Async returns a Promise, await returns then, await terminates execution, try… The catch to capture