Javascript承诺如何进行解析后清理
Javascript Promises how to do post resolution cleanup
我正在努力处理这种特殊情况。我知道我可以用链式回调来解决这个问题,但它似乎几乎是承诺的典型代表:
我有一个父方法,需要按顺序执行三个异步的事情(特别是从用户那里获得确认)。我们称它们为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
);
}
相关文章:
- 承诺在Protractor中进行回调排序
- 基于DOM插入承诺对API调用进行限制
- 如何在AngularJS中承诺控制器后进行单元测试
- 如何对生成的承诺链进行单元测试
- 进行多个 http 调用并使用承诺合并结果
- 在nodejs中使用Q.js承诺进行循环的正确方法
- 在 angularjs 控制器中对承诺调用进行单元测试时遇到问题
- 我可以使用承诺/a 进行事件处理吗?
- JavaScript循环承诺在参数中使用数组进行迭代
- 如何按一系列带有下划线的承诺进行分组
- Angular $q承诺使用摩卡,柴,西农进行单元测试
- 使用承诺进行分页的最佳方式是什么?
- 通过使用解析或拒绝或与承诺(蓝鸟)进行承诺
- 在 javascript 中进行嵌套承诺调用
- 如何进行条件承诺链接
- 使用Q进行承诺投票
- 简化使用$q.defer()进行承诺链接的Angular函数
- 在递归中使用javascript承诺进行Api调用
- Javascript承诺如何进行解析后清理
- 路由器:从canActivate方法返回的承诺中进行重定向