Pay attention to “songbao write code”, selected good articles, a question of the day

Time is always your own

Every minute is also for their future matting and value-added

Saucxs | songEagle

One, foreword

The flag just established on December 23, 2020.One question of the day, the topic type is not limited, can be: algorithm questions, interview questions, elaboration questions and so on.

How can Async/Await Async/Await Async?

A question of the Day

  • How does VUE data binding work?

  • Question 4: How to find repetitive elements in a scientific and efficient way?

  • 3. “Question of the Day” The interviewer asks you what you think of Promise?

  • In ES6, why do we use Symbol?

  • 1. “How does an interview question trigger deep soul searching?”

How to Async/Await Async?

This topic itself is not particularly difficult, can only be said to be as the foundation of recruitment interview questions, but if you want to answer this question is not very easy.

Read on:

1. In a nutshell

If async is added to a function, the function returns a Promise.

Await can only be used in async functions. Think of async as wrapping the return value of a function with promise.resolve ().

Compared with using Promise directly, async and await have the advantage of processing then call chain and writing code more clearly and accurately. The disadvantage is that abusing await can cause performance problems because await blocks code, and perhaps subsequent asynchronous code does not depend on the former but still needs to wait for the former to complete, causing the code to lose concurrency.

Let’s look at a code example:

async function test() {
  return "1";
}
console.log(test()); // -> Promise {<resolved>: "1"}
Copy the code

Let’s look at this example again:

function sleep() {
  return new Promise(resolve => {
    setTimeout(() => {
      console.log('finish')
      resolve("sleep");
    }, 2000);
  });
}
async function test() {
  let value = await sleep();
  console.log("object");
}
test()
Copy the code

The above code prints Finish and then Object. Because await waits for sleep resolve, asynchronous code is not executed after synchronous code, even if it is followed by synchronous code.

2, highlights of the answer

First of all, JS is single threaded (repeat three times), single threaded,

This means that the code is executed line by line (called synchronization),

If it’s not done, it’s just a matter of waiting.

Here’s an example:

function test() { let d = Date.now(); for (let i = 0; i < 1e8; i++) {} console.log(Date.now() - d); Function test1() {let d = date.now (); console.log(Date.now() - d); // 0 } test(); test1();Copy the code

The above is just a for loop, but in practical applications, there will be a large number of network requests, its response time is uncertain, in this case also need to wait?

Obviously not, so JS design asynchronous, namely initiated network request (such as IO operation, timer), due to the need to wait for the server response, first ignore, but to do other things, such as the request to return the result of the time again (that is asynchronous).

So how do you implement asynchrony? Callback: Callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback: callback To learn more, check out the Event-loop mechanism.

In the past, such nested functions and a large number of callback functions made the code difficult to read and unintuitive, so it was vividly called callback hell. Therefore, in order to make writing more popular, ES6 + successively appeared Promise, Generator, Async/await. Strive to be concise and legible in writing.

Async /await is a set of asynchronous processing schemes that refer to Generator encapsulation and can be understood as Generator syntactic sugar.

So to understand async/await we have to talk about Generator, we can talk about this later.

The Generator, in turn, relies on iterators, which we can talk about later.

Finally, the source: one-way linked lists. We’ll talk about that later.

As you can see, async function replaces function*, await replaces yield, and there is no need to write an autoexecutor run by hand

Now let’s look at the features of async/await:

  • ‘Await’ is executed asynchronously when followed by a Promise object, and other types of data are executed synchronously
  • It still returns a Promise object, return ‘done’ in the code above; Will be received directly by the following THEN function

3. Advanced answers

Async /await is a set of asynchronous processing schemes that refer to Generator encapsulation and can be understood as Generator syntactic sugar.

So to understand async/await we have to talk about Generator,

The Generator, in turn, relies on iterators,

So I have to talk about Iterator,

And the idea of Iterator comes from one-way linked lists,

Finally, the source: one-way linked lists

3.1 What is a one-way Linked list?

Linked lists are linear tables that do not store data in a linear order. Instead, they store Pointers to the next node on each node. Because they do not have to be stored sequentially, linked lists can be inserted at o(1) complexity, much faster than the other linear sequential lists, but it takes O (n) time to find a node or access a node with a specific number, whereas sequential lists respond in O (logn) and O (1) time, respectively.

To summarize the advantages of linked lists:

  • No pre-allocated memory is required
  • Insert/delete nodes efficiently without affecting other nodes (typical example: git commit)

One-way linked list: The simplest type of linked list, it contains two fields, an information field and a pointer field. The link points to the next node in the list, and the last node points to a null value.

A one-way linked list contains two values: the value of the current node and a link to the next node

Single link feature: the link direction of the node is unidirectional; Singly linked lists have slower random access speed than arrays, but singly linked lists are very efficient at deleting/adding data.

This is easy to understand if you understand JS prototype chains/scope chains, they are interlinked.

3.2 the Iterator

Let’s take a look at the Iterator first (similar to a one-way list) :

  • Create a pointer object to the start of the current data structure:
  • The first call to the next method of the pointer object points to the first member of the data structure
  • A second call to the next method of the pointer object points to the second member of the data structure
  • Call the next method of the pointer object repeatedly until it points to the end of the data structure

For an object to become iterable, it must implement the @@iterator method. That is, the object (or an object in its prototype chain) must have a property named symbol. iterator (natively: strings, arrays, array-like objects, sets, and maps) :

When an object needs to be iterated over (such as starting for a for.. Of), whose @@iterator method is called with no arguments and returns an iterator used to get the value in the iteration

3.3 the Generator

Generator: The Generator object is returned by the Generator function, complies with the iterable and iterator protocols, is both an iterator and an iterable, and can call the next method, but it is not a function, let alone a constructor.

Calling a generator function does not immediately execute its statements. Instead, it returns an iterator object of the generator. When the iterator’s next() method is called for the first time, the statements in the iterator are executed until the first yield occurs (putting execution in pause). Yield follows the value to be returned by the iterator. Or if yield* (with an asterisk) is used to transfer execution to another generator function (currently suspended by the generator), the next() method is called, and if a parameter is passed, that parameter is returned as the yield statement of the last execution,

To summarize the nature of the Generator, pause, which causes the program to execute at a specified point (yield), then start (next), then stop (yield), then start (next), and this pause makes it easy to associate with asynchronous operations because we are dealing with asynchrony: Start asynchronous processing (network interceding, IO operations), and then pause until the processing is complete. Note, however, that JS is single threaded (again three times), asynchronous or asynchronous, callback or callback, and does not change with the Generator.

3.4 Async/Await

Async /await is a syntactic sugar for Generator, which is a self-executing generate function. Write asynchronous code as “synchronous” using the properties of generate.

I thought that would make it a little clearer.

Reference

  • Developer.mozilla.org/zh-CN/docs/…
  • Es6.ruanyifeng.com/#docs/itera…
  • es6.ruanyifeng.com/#docs/async

All kinds of benefits

“Songbao Code” : development knowledge system construction, technology sharing, project combat, laboratory, one question a day, take you to learn new technology together, summarize the learning process, let you advance to senior engineer, learn project management, think about career development, life perception, enrich grow up. Questions or suggestions, please leave a message on our official account.

1, byte push benefits

Reply “school admission” to get internal push code

Reply “Social recruitment” to get internal promotion

Reply “intern” to get internal push

There will be more benefits later

2. Learning materials welfare

Reply “Algorithm” to obtain algorithm learning materials

3. One question of the day

  • How can Async/Await Async/Await Async?

  • Question 5: How does VUE data binding work?

  • Question 4: How to find repetitive elements in a scientific and efficient way?

  • 3. “Question of the Day” The interviewer asks you what you think of Promise?

  • In ES6, why do we use Symbol?

  • 1. “How does an interview question trigger deep soul searching?”