2017-04-18 83 views
3

我试图用一种新方法来扩展javascript的承诺。在这种情况下,这种新方法被称为foo,这确实是这样的:扩展内置javascript Promise

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

因此,在短期,把foo()函数是在等待一个承诺来解决,然后调用foo的快捷方式()上结果。

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

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

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

这是我已经试过:

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这给了我:

TypeError: calling a builtin Promise constructor without new is forbidden 

在节点:

TypeError: #<Promise> is not a promise 

这仅仅是一个JavaScript的限制,或者有没有办法解决这个问题?

+2

也许你应该使用'FooPromise.prototype.foo' - 因为你将使用FooPromise的实例(为什么不把它添加到Promise.prototype.foo中,而不是使用FooPromise) - 作为因为你试图从承诺“继承” - 它看起来3种错误开始 –

+0

请参阅[延迟链接承诺](http://stackoverflow.com/questions/38734106/delay-chained-promise/38734306#38734306) – guest271314

+0

什么是'result.foo'? – guest271314

回答

0

更多的研究后,我登上了以下解决方案。没有必要扩展内置的Promise。你真正需要的是确保你的对象正确实现then(又名Promise/A + /可用)。

function FooPromise(executor) { 

    this.innerPromise = new Promise(executor); 

} 

FooPromise.prototype = { 

    function then(onFulfilled, onRejected) { 

    return new FooPromise(function(res, rej) { 

     this.innerPromise.then(res, rej); 

    }); 

    } 

    function foo() { 

    return this.then(function(val) { 

     return val.foo(); 

    }); 

    } 

} 

这在ES5环境中工作正常,与其他承诺完全一致,甚至异步/等待(如果可用)。

我成功实施了这种模式this open source library

6

ES6方式:

class FooPromise extends Promise { 
    constructor(executor) { 
     super(executor); 
    } 
} 

var fooPromise = new FooPromise((resolve,reject)=>{ 
    resolve(null); 
}); 
+0

__TypeError__:承诺的执行者必须是一个函数。当然是 – traktor53

+0

!例如:'var fooPromise = new FooPromise((resolve,reject)=> {resolve(1);});' – 2017-04-18 06:13:31

+0

非常感谢您的更新。 – traktor53