无论承诺履行如何,如何执行相同的操作? [英] How to perform same action regardless of promise fulfilment?

查看:29
本文介绍了无论承诺履行如何,如何执行相同的操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在一个承诺被成功或失败完成后执行相同的操作,即我想对成功和错误处理程序执行相同的操作,然后继续发送承诺的结果到适当的错误/成功处理程序.

I would like to perform the same action after a promise has either been fulfilled with a success result or failure, ie I want to perform the same action for the success and error handler and then continue to send down the result of the promise to the appropriate erroe/success handlers.

var pleaseWaitPromise = playAudioAsync("please wait");

myLongRunningPromise().then(function tempSuccessHandler(result) {
  pleaseWaitPromise.cancel();
  return result;
}, function tempErrorHandler(error) {
  pleaseWaitPromise.cancel();
  return WinJS.Promise.wrapError(error);
}).done(function realSuccessHandler(result) {
  console.info(result);
}, function realError(error) {
  console.error(error);
});

有没有更优雅的方法来停止pleaseWaitPromise,它也可以是一个函数调用而不是一个promise(比如clearInterval)

Is there a more elegant way to stop the pleaseWaitPromise, which could also be a function call instead of a promise (like clearInterval)

推荐答案

jfriend 是正确的,您通常希望 finally 在这里 - 它与您上面的代码所做的完全一样.遗憾的是,WinJS 承诺目前没有 .finally 功能,所以除非你想填充它(在 WinJS.promise 的原型上修补它),否则你会被它卡住.

jfriend is right you'd typically want finally here - it does exactly what your code above does. Sadly WinJS promises do not feature .finally at the moment so unless you'd like to shim it (patching it on the prototype of WinJS.promise) you're stuck with it.

你也可以把它当作一个函数:

You can also put it as a function:

function always(prom, fn){
     return prom.then(function(v){ fn(v); return v; },
                      function(e){ fn(e); return WinJS.Promise.wrapError(error); });
}

看起来像:

always(myLongRunningPromise(),
  pleaseWaitPromise.cancel();
})).done(function realSuccessHandler(result) {
  console.info(result);
}, function realError(error) {
  console.error(error);
});

这篇关于无论承诺履行如何,如何执行相同的操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆