JavaScript本机Promise在两个结果上执行回调 [英] JavaScript native Promise execute callback on both results

查看:92
本文介绍了JavaScript本机Promise在两个结果上执行回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在Promise对象的两个结果上执行回调?

Is there any way to execute callback on both results of Promise object?

例如,我想在执行xhr请求后制作一些清理逻辑。所以我需要做这样的事情:

For example I want to make some cleanup logic after execution of xhr request. So I need to do something like this:

var cleanUp = function() { something.here(); }
myLib.makeXhr().then(cleanUp,cleanUp);

在jquery中提到例如我可以使用方法always():

In jquery Defered for example i can use method always():

myLib.makeXhr().always(function() { something.here(); });

Promise是否支持这样的事情?

Does Promise support something like this?

推荐答案

不,没有。这是讨论了但规格很小。它不包括许多其他功能。它旨在与图书馆承诺良好互操作,并提供简单的功能。

No, there is none. It was discussed but the spec is minimal. It doesn't include a bunch of other functionality. It's designed to interoperate well with library promises and to provide simple functionality.

这是一个正确的polyfill最初由StefPanner提出的提案

此外,我不同意当前现已删除的答案,因为它们是自己添加的一切都做错了(作为一个可枚举的财产 - 没有乐趣)。即使我们忽略它对返回值的返回值和错误状态的作用。扩展原生承诺的预期方法是继承它们,遗憾的是,没有浏览器支持这个,所以我们必须等待。

Moreover, I disagree with the current now deleted answers adding it themselves because they're all doing it wrong (as an enumerable property - no fun). Even if we ignore what it does to the return values and error state of the returned promise. The intended way to extend native promises is by subclassing them, sadly, no browsers support this yet so we'll have to wait.

如果弄乱本机原型,我们应该使用不同的模式:

Instead of messing with native prototypes, we should use a different pattern:

openDb().then(foo).then(bar).finally(close).then(more);

即使我们在应用程序中打开100次,忘记打电话也很容易忘记打电话关闭它甚至一次仍然是毁灭性的。另一方面 - 我们可以使用一些承诺库提供的处理器模式:

Is susceptible to us forgetting to call close, even if we open it 100 times in our app, forgetting to close it even once can still be devastating. On the other hand - we can use the disposer pattern which some promise libraries provide built in ourselves:

openDb(function(db){
    return foo(db).then(bar);// chain here
}).then(more);

基本上 - 这种模式意味着没有 openDB 返回一个promise - 我们需要一个函数返回一个promise,当函数运行时,如果它返回一个promise我们等待该promise的解析。它看起来像:

Basically - this pattern means instead of having openDB return a promise - we have it take a function and return a promise, when the function is run, if it returns a promise we wait for that promise to resolve. It looks something like:

function openDb(withDb){
    return justOpenWithoutCleanUp().
           then(withDb).
           then(clean, function(e){ clean(); throw e; }); // note the rethrow
}

这篇关于JavaScript本机Promise在两个结果上执行回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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