sequencing function calls in javascript - are callbacks the only way?

后端 未结 5 549
谎友^
谎友^ 2021-02-03 11:25

I read through various threads like this one for example.

But it really escapes me how to accomplish the following:

I have 4 functions, and want them happen one

5条回答
  •  孤独总比滥情好
    2021-02-03 11:56

    I have played with the Promise, Sequence, Exception, Callback to understand how it works and finally made this code.

    Call functions with callback and send result as parameter to another function in sequence and have a catch errors.

    function firstFunction(par) {
        return new Promise(function (resolve, reject) {
            console.log("start " + par);
            setTimeout(function (par) {
                console.log(par);
                resolve(par + 1);
            }, 1000, par);
        });
    }
    function secondFunction(par) {
        return new Promise(function (resolve, reject) {
            console.log("start " + par);
            setTimeout(function (par) {
                console.log(par);
                try{
                    throw "Let's make an error...";
                }
                catch(err)
                {
                    reject(err);
                }
                resolve(par + 1);
            }, 1000, par);
        })
    }
    function thirdFunction(par) {
        return new Promise(function (resolve, reject) {
            console.log("start " + par);
            setTimeout(function (par) {
                console.log(par);
                resolve(par + 1);
            }, 1000, par);
        });
    }
    
    function CatchError(error) {
        console.log("Exception: " + error);
    }
    
    //Break all chain in second function
    function ChainBrake() {
        firstFunction(1)
        .then(secondFunction)
        .then(thirdFunction)
        .catch(CatchError);    
    }
    
    //Log error and continue executing chain
    function ChainContinue() {
        firstFunction(1)
        .catch(CatchError)
        .then(secondFunction)
        .catch(CatchError)
        .then(thirdFunction)
        .catch(CatchError);
    }
    

提交回复
热议问题