I just wrote array reduce notes a few days ago, and I didn’t expect to use it so soon.


scenario

Here’s how it works

There is a page with three channels of advertising to be loaded in the WAY of API display roughly as shown below



I’ve encapsulated the different types of exposure clicks for each of the three ads

Just load the data to add AD types and merge different AD data into a list that can be used directly

But the order of the three ads has been changed frequently recently

Because these are asynchronous fetches, you can either wait for all three to load and then process them or load them sequentially

But the first one is going to take a lot of time and you just have to process the pass names sequentially and that becomes a callback purgatory so I have to keep changing the logic of the load order

To solve

Today, I suddenly had a flash of inspiration. The reduce aggregation washed a few days ago is just dealing with this kind of event, but the original is synchronous need to be changed to asynchronous, so I made some modifications to try the code as follows

function compose(... Funcs){return funcs.reduce((curr,prev)=>{funcs){return funcs.reduce((curr,prev)=>{// Async and await return async (... args)=>{await prev(await curr(... args)) }}) }Copy the code

We can see that we are just adding async and await to indicate that the function to be executed is asynchronous, so we pass in a function that returns a Promise

Return new Promise((resolve)=>{setTimeout(()=>{console.log('f1 done ')) resolve() },1000)} function f2(){console.log(' perform f2') return new Promise((resolve)=>{setTimeout(()=>{console.log(' finish f2')) Resolve ()},1000)})} function f3(){console.log(' perform f3') return new Promise((resolve)=>{setTimeout(()=>{setTimeout()=>{ The console. The log (' f3 finish) resolve ()}, 1000)})} / / calls to compose (f1, f2 and f3) ()Copy the code

The output is as follows

And then change the order

compose(f3,f2,f1)()
Copy the code

Ok perfect now a single function only needs to concatenate a global variable and then simply change the order in which the functions are executed


It feels suitable for some scenarios where continuous asynchronous calls exist and there is a chain of call relationships

Hopefully this will give you some new ideas for development