As the ES6 standard of JS, Promise has officially entered the browser environment and Node. JS environment. However, for the needs of programmers, the current Promise function is still a little inadequate, for example, I want to set a group of Timeout how to do?

Traditional synchronization methods are simple to implement

let count = 10;
const func = (a)= > {
    if(count > 0) {
        setTimeout(func, 1000);
        count -= 1; }}Copy the code

So we can do 10 times, 1 second at a time, isn’t that easy?

But now the problem is to do it asynchronously, so stick with the old method and see what happens

let count = 10;

const func = async() = > {if(count > 0) {
        setTimeout(func, 1000);
        count -= 1; }}Copy the code

Well… It doesn’t seem to be a problem, is it? Think carefully about the type of func. The type of func is Function in synchronous methods, but is it also Function in asynchronous methods? NO! No, the func type in asynchronous methods is Promise! OK, so the question is, how can you use setTimeout(function, timeout) if func is a Promise? You don’t pass too many types, so you can’t execute them!

So what are the methods for implementing asynchronous timed calls? After all, sometimes we need to test the network transmission. When the network condition is bad, we hope to test the network connection periodically to obtain the network condition. Here we use the method promise.race (), you may say why not bluebird library, there are also methods to implement it. I want to remind you that promise.race () is a method that is currently provided natively on both the browser side and node.js side, so it can be implemented with higher portability. Now let’s imagine a scenario where we need to connect to a remote server, but there is no guarantee of 100% success. So you need to ping the server to see if it’s still alive

const axios = require('axios');// Maximum number of connection retries
const MAX_RETRYS = 10
let count = 0;

@method {Function} reject (); /** * test whether the server is alive * @method {Function} reject ()
const ping = async (resolve, reject) => {
    constresponse = axios.get(...) ;if(response.status === 200) {resolve(); }else if(count > MAX_RETRYS) {reject(); } count +=1;
}

// The following are asynchronous timed invocation methods
// Ping again every 1 second
const tasks = [...Array(MAX_RETRYS + 1).keys()].map(i= > {
    return new Promise((resolve,reject) = > {
        setTimeout(ping(resolve, reject), i * 1000)})})// Handle pinging
tasks.race().then((a)= > {.../* Successful subsequent execution */})
.catch((a)= > {.../* Failed subsequent execution */})
Copy the code

Here the method I use is produced by a set of tasks to simulate the time interval, so to understand, when I was at time 0 to ping, moment to ping 1 second, time for 2 seconds to ping, and so on to produce a set of tasks, ping to execute, when moment to effect similar to synchronized methods, But one thing that’s different from the synchronous method is that the queue can’t be infinite, so you have to set a maximum number of attempts, which is actually what we would set in practice. You can’t wait an hour for the user to connect to the server

[…Array(MAX_RETRYS+1).keys()] this method is similar to python’s range() function, but Javascript does not have a native implementation, so ES6 features are used instead. Simple simulation of the range() function, the specific meaning of you see the official documentation, very simple

I hope this method is helpful to you