Javascript承诺如何进行解决后清理

时间:2015-08-29 21:27:31

标签: javascript ecmascript-6 es6-promise

我正在努力解决这个特殊情况。我知道我可以通过链式回调解决这个问题,但它似乎几乎是承诺的典型代表:

我有一个父方法,需要按顺序执行三个异步事项(特别是从用户那里获得确认)。我们称它们为func1 func2和func3。现在我可以让每一个都返回一个承诺并链接那些,这一切都很有效。我遇到的问题是:

func1需要设置一个状态,等待链的其余部分运行,然后取消设置该状态。

演示伪代码:

function wrapper(){
    func1()
        .then(func2())
        .then(func3());
}
function func1(){
    return new Promise(function(resolve, reject){
        //do some async stuff that itself returns a promise :)
        async1().then(function(value){
            //set some global states based on the value for the duration of this chain
            resolve(); //Note NOT returning value as it's irrelevant to the other functions
            //!!! clean up the global states regardless of future failure or success, but after one of those.
        }, reject); //if async1 rejects, just pass that right up.
    });
}
function func2(){
    //do some logic here to decide which asyn function to call
    if (/*evaluates to */true){
        return async2(); //another async function that returns a promise, yay!
    } else {
        return async2_1(); //also returns a promise.
    }
}
function func3(){
    //do some dom updates to let the user know what's going on
    return Promise.resolve(async3()).then(function(){
        //update the dom to let them know that everything went well.
    });//returns this promise chain as a promise which the other chain will use.
}

我正在努力的部分是在resolve()之后的func1中的行;请注意,正如我所说的那样,我在func1中调用的async1确实返回了一个promise,所以我已经在这里使用了很多promises。我需要在func3结果返回的承诺之后进行清理。

理想情况下,这将以某种方式包含在func1中,但我也可以使用半全局变量(整个块将包含在更大的函数中)。

1 个答案:

答案 0 :(得分:2)

您想要使用disposer pattern(并避免使用Promise constructor antipattern):

function with1(callback) {
    return async1() // do some async stuff that itself returns a promise :)
    .then(function(value) {
        // set some global states based on the value for the duration of this chain
        const result = Promise.resolve(value) // or whatever
        .then(callback);

        return result.then(cleanup, cleanup);
        function cleanup() {
            // clean up the global states regardless of the failure or success of result
            return result;
        }
    });
}

你可以像

一样使用它
function wrapper() {
    with1(() =>
        func2().then(func3) // whatever should run in the altered context
    );
}