This is the third day of my participation in the August More text Challenge. For details, see: August More Text Challenge

preface

In the previous article, we have talked about the basic use of ES6 Reduce. I believe that after reading the children’s shoes, we should be able to fully grasp the basic use of Reduce. This article can be said to be a supplement to the last one. I’m going to talk about how to use Reduce to implement asynchronous serialization gracefully.

What is the asynchronous

Asynchronous (async) is the opposite of Synchronous (sync). In traditional single-threaded programming, as we learned, the program runs synchronously (synchronously does not mean that all the steps run simultaneously, but rather that the steps are executed sequentially in a sequence of control flows). The concept of asynchronous is the concept of non-guaranteed synchronization, that is, the execution of an asynchronous process will no longer have a sequential relationship with the original sequence. To put it simply, synchronization is in the order of your code. Asynchronous is not in the order of your code. Asynchronous is more efficient.

This is an explanation of the concept of asynchrony. Let’s explain asynchrony in general terms: Asynchrony is to send a child thread from the main thread to complete a task.

So back to the topic, how do you implement an asynchronous serial?

Asynchronous serial port

Reduce constructs continuous Promise callbacks

Reduce is the traversal stack method in ES6, which is handy for constructing continuous Promise callbacks at some point.

A simple example:

Suppose there are a lot of request interfaces, they have dependencies, they have to wait for the end of the first request to request the second, and so on, how to achieve this requirement?

let list = [
  'www.baidu.com?a=1'.'www.baidu.com?b=1'.'www.baidu.com?c=1'. ]Copy the code

This is an asynchronous serialization problem. A simple way to do this is to use async await with a for loop:

async function fun(){
    for(let i=0; i<list.length; i++){awaitaxios.get(list[i]); }}Copy the code

In addition to the above methods, you can also use Reduce,

list.reduce((pre,next) = >{
    return pre.then(() = >axios.get(next));
},Promise.resolve())
Copy the code

Promise.resolve is the initial value of reduce, and the pre-then traversed for the first time is promise.resolvely.then (); Return an AXIos.get (next) Promise each time, and then the next time you iterate, use the Promise followed by a then.

list.reduce(async (pre,next)=>{
    await pre;// Wait for the last Promise
    return axios.get(next);// Return a new Promise
},Promise.resolve())
Copy the code

A simple asynchronous serial implementation, is not very concise.

Want to learn more development skills, pay attention to the public: front-end development enthusiasts learn front-end skills together