我有一个函数,它返回一个可解析为对象的promise。
我希望此对象有一个事件,每次在内部调用此事件时,我都可以收听。
使用伪代码,它看起来像这样:
// function that returns the promise
function myFunction(){
return new Promise(function(resolve, reject) {
var obj = {};
obj.running = event; // this is a fake line of code
setInterval(function(){
obj.running // this should trigger
}, 3000); // something that can be listened to
resolve(obj);
});
}
// function that can listen to the event
myFunction().then(function(obj){
obj.event(){ // Fake event listener
alert("the set interval function from the code above just ran")
}
})
我可以想到的使用真实代码完成此操作的唯一方法是使用内部setInterval方法触发时调用的函数来原型化已解析的对象。
但是,我希望这样做而无需使用原型来简化功能API。现实生活中还有其他方法吗?
问题是您要在广播员之后设置监听器。理想情况下,应该在创建广播者之前创建侦听器,以便侦听器可以收听每个广播。
无论如何,一种方法可能是使用外部对象作为事件的持有者,以便首先创建侦听器。
var object = {
running: function(){ }
};
// function that returns the promise
function myFunction(object){
return new Promise(function(resolve, reject) {
setInterval(function(){
object.running(); // this should trigger
}, 3000); // something that can be listened to
});
}
// function that can listen to the event
myFunction(object).then(function(response){
object.running = function() {
//do stuff here;
};
});
这个想法是创建一个包含伪函数的对象,然后在promise解析后更改该函数。我了解这似乎不是最好的解决方案,但这是我在使用香草javascript时想到的唯一方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句