How to implement a task queue with Promise

encountered a business requirement at work.
implements a task queue, and then executes the next task after the previous task has been executed. I wanted to implement an asynchronous serial queue with promise. But this time the situation is different. After thinking about it for a while, I can"t figure it out. Ask the boss for advice.

the business scenario abstracts as follows:
there is the following task queue T = [A br B]
and there is already a listening function F = onStateChange (res = > "res is the value I want to judge")
An and B both install a run method (return promise), this method executes a logic that triggers a State change, and then decides whether it is resolve or reject based on the value of res

the concrete example is:
Mini Program needs to send several instructions to the Bluetooth device to connect to Bluetooth according to whether the previous instruction is passed or not before the next instruction can be carried out.

Mar.20,2021

in your opinion, the state of each task is going to be completed, right?
suppose your listener function listens to the variable State , then the value of this variable is judged at the end of each task to decide whether to exit or not.


// 

var T = [];
//
function onStateChange(){
    //
    return Promise.resolve(Math.random() > 0.5) ;
}
// 10
function taskFactory(){
    for(var i=0;i<10;iPP){
        T.push(
            {
                name: i,
                run: function(){
                    var self = this;
                    return new Promise(function(resolve,reject){
                        
                        //onStateChange 
                        onStateChange().then( function(isResolve){
                            if(isResolve){
                                console.log('' + self.name);
                                resolve('' + self.name);
                            }else{
                                console.log('' + self.name);
                                reject('' + self.name);
                            }
                        })
                    })
                }
            }
        )
    }
}

// 
taskFactory();

//
var index = 0;

//
function doTask(){
    if(index == T.length-1){
        return Promise.resolve('');
    }
    return new Promise(function(resolve,reject){
        T[index].run().then(function(result){
            index PP;
            resolve(doTask());
        }).catch(function(failresult){
            resolve(failresult);
        });
    });
}

// 
doTask().then(function(result){
    console.log("result:" + result);
});

Menu