In the previous chapter we looked at asynchronous programming solutions that combine CO and Generator.

I know what you’re saying, writing an asynchronous call also involves importing an NPM package (albeit one written by TJ).

Mom sold approved NPM!

Of course it doesn’t exist. If a feature is important enough and the community is vocal enough, it will be included. In a moment, we will introduce aisin Gioro Async, the ultimate heir of the pure asynchronous programming family.

To:

  1. Chapter 1: Event loops in detail Async topic
  2. Chapter 2: A detailed description of late promises Async
  3. Chapter 3: State machine Async topic in detail
  4. Part 4: A detailed description of Async, perhaps the ultimate asynchronous solution
import co from 'co';

function fetchByName(name) {
    const url = `https://api.github.com/users/${name}/repos`;
    return fetch(url).then(res= > res.json());
}

co(function *gen() {
    const value1 = yield fetchByName('veedrin');
    console.log(value1);
    const value2 = yield fetchByName('tj');
    console.log(value2);
});
Copy the code
function fetchByName(name) {
    const url = `https://api.github.com/users/${name}/repos`;
    return fetch(url).then(res= > res.json());
}

async function fetchData() {
    const value1 = await fetchByName('veedrin');
    console.log(value1);
    const value2 = await fetchByName('tj');
    console.log(value2);
}

fetchData();
Copy the code

Look at the seamless upgrade experience.

flexible

Don’t be put off by the new keyword, it’s actually quite flexible.

async function noop() {
    console.log('Easy, nothing happened.');
}
Copy the code

Can this guy execute? Of course you can. Your old buddy’s still your old buddy.

async function noop() {
    const msg = await 'Easy, nothing happened.';
    console.log(msg);
}
Copy the code

Again, don’t panic. Just as expected.

It is only when the await keyword is followed by a Promise that it shows the power of asynchronous control, otherwise it is harmless.

function fetchByName(name) {
    const url = `https://api.github.com/users/${name}/repos`;
    return fetch(url).then(res= > res.json());
}

async function fetchData() {
    const name = await 'veedrin';
    const repos = await fetchByName(name);
    console.log(repos);
}
Copy the code

Although we can handle both Promise and non-promise after saying await keyword, they are treated differently. A non-promise expression simply returns its value, whereas a Promise expression waits for its state to change from Pending to depressing, and then returns the resolve parameter. It’s doing something implicit.

Note that fetchByName(‘veedrin’) logically returns a Promise instance, but the repos value we get is an array, and this is where the await keyword is processed implicitly.

What else do you need to notice? The await keyword can only be defined in async functions.

const then = Date.now();

function sleep(duration) {
    return new Promise((resolve, reject) = > {
        const id = setTimeout((a)= > {
            resolve(Date.now() - then);
            clearTimeout(id);
        }, duration * 1000);
    });
}

async function work() {[1.2.3].forEach(v= > {
        const rest = await sleep(3);
        console.log(rest);
        return 'Awake';
    });
}

work();

// Uncaught SyntaxError: await is only valid in async function
Copy the code

Okay, so let’s put it in a scope.

import sleep from './sleep';

function work() {[1.2.3].forEach(async v => {
        const rest = await sleep(3);
        console.log(rest);
    });
    return 'Awake';
}

work();
Copy the code

Sorry, the ‘wake up’ return does not wait for the asynchronous operation to complete, which is probably not what you want.

So in this case, you have to use a for loop instead and async and await can stay together.

import sleep from './sleep';

async function work() {
    const things = [1.2.3];
    for (let thing of things) {
        const rest = await sleep(3);
        console.log(rest);
    }
    return 'Awake';
}

work();
Copy the code

Return a Promise instance

Some say async is the syntactic sugar of Generator.

Naive, friends.

Async is more than one candy. It is a wrapper around Generator, CO, and Promise. If the Generator is just a state machine, async is designed for asynchrony.

import sleep from './sleep';

async function work() {
    const needRest = await sleep(6);
    const anotherRest = await sleep(3);
    console.log(needRest);
    console.log(anotherRest);
    return 'Awake';
}

work().then(res= > console.log('🙂', res), res => console.error('😡', res));
Copy the code

Since async returns an instance of Promise, where does the value of its return go? It becomes the argument passed in the returned Promise instance Resolve. In other words, return ‘wake up’ internally becomes resolve.

I can guarantee that a real Promise instance is returned, so the rest of the features should follow Promise’s lead.

concurrent

As you may have noticed, the example in the previous section took more than 9 seconds to finally finish executing. But there is no dependence between the two sleeps. Why do I have to wait nine seconds?

I told you to do asynchronous flow control, didn’t I? Now you’re talking to me about concurrency!

I… To meet you.

import sleep from './sleep';

async function work() {
    const needRest = await Promise.all([sleep(6), sleep(3)]);
    console.log(needRest);
    return 'Awake';
}

work().then(res= > console.log('🙂', res), res => console.error('😡', res));
Copy the code
import sleep from './sleep';

async function work() {
    const onePromise = sleep(6);
    const anotherPromise = sleep(3);
    const needRest = await onePromise;
    const anotherRest = await anotherPromise;
    console.log(needRest);
    console.log(anotherRest);
    return 'Awake';
}

work().then(res= > console.log('🙂', res), res => console.error('😡', res));
Copy the code

There’s more than one way. The trick is the same, just move “await” backwards so that you can hold it and achieve concurrency.

Great summary

Knowledge of asynchrony can be roughly divided into two broad chunks: asynchronous mechanics and asynchronous programming.

The essence of asynchrony is the event loop.

Inversion of control (from notifying the main thread of events to polling the main thread for events) perfectly solves the problem of a thread being too busy.

Asynchronous programming has come a long way from callbacks to promises to Async. The essence of asynchronous programming is to deal with asynchronous mechanisms in as close to synchronous syntax as possible.

At present, Async is a perfect solution for synchronous asynchronous programming.

But in fact async is deeply integrated with Promise, which can be said to be the underlying dependency of Async. Not only that, but many apis, such as FETCH, use Promise as an underlying dependency.

So the Promise is the Promise of asynchronous programming.

In what way is Promise asynchronously programmed? By then functions, which in turn are resolved by callbacks.

So callbacks are something that’s written into the asynchronous programming DNA. Your big brother or your big brother!

An inversion is also called an event.

Now you understand why JavaScript is event driven? Github.com/veedrin/hor…

❤️ watch two little things

If you find this article inspiring, I’d like you to do me two small favors:

Share this article with your friends/communication group, let more people see it, progress together, grow together!

Pay attention to the public number “IT square head brother alliance”, the public number background reply “resources” free of charge to get my carefully organized front-end advanced resources tutorial

  • More articles
  • React vs Angular vs vue.js — Who to pick for 2019?
  • VS Code 1.41 released! VS Code Web edition has enhanced support for macOS or iPadOS
  • Big front-end trends for 2020

www.javascriptC.com is a platform dedicated to helping developers change the world with code. You can find the top content in the technology world here every day