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

Javascript Promises how to do post resolution cleanup

本文关键字:承诺 何进行 Javascript      更新时间:2023-09-26

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

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

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确实返回一个承诺,所以我已经在这里使用了很多承诺。我需要在从func3返回的承诺解析后进行清理。

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

您需要使用处理器模式(并避免使用Promise构造函数反模式):

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
    );
}