async

Async /await in JavaScript is the syntactic candy of promise, which is both tasty and sweet. With the exception of Internet Explorer, most browsers already support this feature. To be clear, async and await do not have to be used together!

1. Async is used alone

async function foo(a) {
   return 1
}
Copy the code

This is equivalent to:

function foo(a) {
   return Promise.resolve(1)}Copy the code

Output result:

 Promise {<fulfilled>: 1}
Copy the code

The async function returns a Promise object. If an immediate quantity is returned in the function, async wraps the immediate quantity into a Promise object with promise.resolve ().

2, await

Note that await must go with async otherwise an error will be reported.

function dosomething(a) {
    return "dosomething";
}

async function Async(a) {
    return Promise.resolve("async");
}

async function test(a) {
    const v1 = await dosomething();
    const v2 = await Async();
    console.log(v1, v2);
}

test();
Copy the code

Results:If an await object is not a Peomise object, it outputs the await result directly. If an await object is a Promise object, it blocks the following code until the result is returned.One might ask what if the return value is reject?

async function test(a) {
  try {
    await anythingelse(a);
  } catch (err) {
    console.log(err); }}Copy the code

// Another way to write it

async function test(a) {
  await anythingelse(a).catch(function (err){
    console.log(err);
  });
}
Copy the code

3. How to gracefully handle callbacks?

function takeLongTime(n) {
    return new Promise(resolve => {
        setTimeout(() => resolve(n + 200), n);
    });
}

function step1(n) {
    console.log(`step1 with ${n}`);
    return takeLongTime(n);
}

function step2(n) {
    console.log(`step2 with ${n}`);
    return takeLongTime(n);
}

function step3(n) {
    console.log(`step3 with ${n}`);
    return takeLongTime(n);
}
Copy the code

How do I execute steps sequentially?

async function doIt(a) {
    console.time("doIt");
    const time1 = 300;
    const time2 = await step1(time1);
    const time3 = await step2(time2);
    const result = await step3(time3);
    console.log(`result is ${result}`);
    console.timeEnd("doIt");
}

doIt();
Copy the code

The results:

Sweet not sweet?