This is the third day of my participation in the August Text Challenge.More challenges in August

In order to address the readability of asynchronous operations to code and avoid callback hell (the nested condition of many asynchronous callbacks), the JavaScript community retired the Promise+ THEN and Generator + CO solutions to async/await, the ultimate asynchronous programming solution, The ability to access resources asynchronously can be achieved by writing synchronous code without blocking the main thread, and the code logic is clearer. Async /await uses both Generator and Promise technologies. Promise can take a look at eight pieces of code to thoroughly grasp the Promise, here only sketcher concept.

Generators and coroutines

Concepts related to generator functions
  • function*The declared function is the generator function,If the yield keyword is encountered during code execution inside a generator function, the JavaScript engine returns the content following the keyword externally and suspends execution of the function.
  • Next () returns an object with both value and done. Value is the value after Yeild, and done is a Boolean value indicating whether the generator has finished executing, which is true.
Function * genDemo() {console.log(" start executing first paragraph ") yield 'generator 1' console.log(" start executing second paragraph ") yield 'generator 2' Console. log(" start execution third paragraph ") yield 'generator 3' console.log(" finish execution ") return 'generator over'} console.log('main 1') let gen =  genDemo() console.log(gen.next().value) console.log('main 2') console.log(gen.next().value) console.log('main 3') console.log(gen.next().value) console.log('main 4') console.log(gen.next().value) console.log('main 5')Copy the code
coroutines

Coroutines is the existence of A more lightweight than threads, task is run on the thread, A thread on the exist many collaborators, but at the same time in the thread can only perform A collaborators, if A coroutines running at this time, need to start the B coroutines, then A coroutines will need to take control of the main thread to B coroutines, suspended at this time A coroutines, B coroutines resume execution, in the same way, A coroutine can also be started from B coroutine. If B coroutine is started from A coroutine, the A coroutine is called the parent of the B coroutine.

A process can have multiple threads, a thread can also have multiple processes, the coroutine is not controlled by the operating system, but the program manipulation, the advantage is that the performance can be improved a lot, as thread switching does not consume resources.

Let’s look at the above code again:

  • First of all,let gen = genDemo()Instead of executing it, the Gen coroutine is actually created
  • The coroutine then executes Gen. Next (), and when gen. Next () is executed, the coroutine will resume execution
  • On execution of the yeild keyword in the coroutine, the coroutine stops execution, returns the MSG message in yeild ‘MSG’, and surrenders execution of the main thread
  • When a coroutine gen encounters a return during execution, the JavaScript engine terminates the current coroutine and returns the content after the return to the parent coroutine (creating his coroutine).

Combine generator functions with promises

fetch('https://juejin.cn/').then(function(){
    console.log('success')
})
Copy the code
function* foo(){ let response1 = yield fetch('https://juejin.cn/') console.log('response111') let response2 = yield Fetch ('https://www.Anblog.top') console.log('response222')} // create gen coroutine let gen = foo() // get returned Promise object function GetGenPromise (gen){return gen.next().value} GetGenPromise (gen).then((response)=>{console.log('response1')) console.log(response) return getGenPromise(gen) }).then((response)=>{ console.log('response2') console.log(response) })Copy the code

Steps:

  1. Create the generator foo function.
  2. let gen = foo()Create the Gen coroutine
  3. creategetGenPromise(gen)Function that executes and results in the execution of gen.next().value, which transfers execution of the main thread to the gen coroutine
  4. getGenPromise(gen)Return the Promise object, and then execute the FETCH function on the Gen coroutine. Then passes in the response from the Promise object returned by the FETCH function. The first THEN function executes and returnsgetGenPromise(gen)The result is given to the response parameter of the next then, which is then executed.

In general, the code of the generator is encapsulated into a function, and the function of the generator is called the executor. The above is a process of the generator and Promise cooperating with each other. However, we usually wrap the part of the execution generator into a function.

The co framework can be used to simplify the code. The CO function can replace the above code of the execution generator, and the CO function can also be called the executor.

const co = require("co");
const fetch=require("node-fetch")
function* foo(){
    let response1 = yield fetch('https://juejin.cn/')
    console.log('response111')
    let response2 = yield fetch('https://www.Anblog.top')
    console.log('response222')
}
co(foo());
Copy the code