扩展内置的JavaScript承诺 [英] Extending the built-in javascript Promise

查看:65
本文介绍了扩展内置的JavaScript承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用新方法扩展javascript承诺。在这种情况下,这种新方法称为 foo ,它实际上是这样的:

I'm trying to extend the javascript promise with a new method. This new method in this case is called foo, which really does something like this:

Promise.foo = function(arg) {
  return this.then( function(result) {
    return result.foo(arg);
  });
};

因此,简而言之,foo()函数是等待承诺解决的快捷方式,然后在结果上调用foo()。

So in short, the foo() function is a shortcut for waiting for a promise to resolve and then calling foo() on the result.

这个函数的本质是它可以链接,就像 then()可以。

The nature of this function is that it can be chained, just like then() can.

myPromise.foo(a).foo(b).foo(c);

我觉得这应该是可能的,但我只是不确定正确的道路是什么。

I feel like this should be possible, but I'm just not sure what the right path is.

这是我试过的:

var FooPromise = function() {
   Promise.apply(this, arguments);
}

FooPromise.prototype = Object.create(Promise.prototype);
FooPromise.foo = function(arg) {
  return this.then( function(result) {
    return result.foo(arg);
  });
};

测试一下:

var test = new FooPromise(function(res, rej) {
   res('bla');
});

在Firefox中,这给了我:

In firefox this gives me:

TypeError: calling a builtin Promise constructor without new is forbidden

In节点:

TypeError: #<Promise> is not a promise

这只是javascript的限制,还是有办法解决这个问题?

Is this just a limitation of javascript, or is there a way around this?

推荐答案

经过更多研究,我找到了以下解决方案。没有必要扩展内置的Promise。你真正需要的是确保你的对象正确实现然后(又名Promise / A + / thenable)。

After more research, I landed on the following solution. There's no need to extend the built-in Promise. All you really need is to make sure your object implements then correctly (aka Promise/A+ / thenable).

function FooPromise(executor) {

  this.innerPromise = new Promise(executor);

}

FooPromise.prototype = {

 then: function(onFulfilled, onRejected) {

    return new FooPromise(function(res, rej) {

       this.innerPromise.then(res, rej);

    });

  },

  foo: function() {

    return this.then(function(val) {

      return val.foo();

    });

  }

}

这个工作正常在ES5环境中,与其他promises完美配合,甚至async / await(如果可用)。

This works fine in ES5 environments, works perfectly with other promises and even async/await (where available).

我成功实现了这种模式这个开源库

I successfully implemented this pattern this open source library.

这篇关于扩展内置的JavaScript承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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