如何多次解决承诺? [英] How to resolve a promise multiple times?
问题描述
这可能听起来很奇怪,但我正在寻找一种方法来多次解决承诺。有没有办法让这成为可能?
It might sound weird, but I'm looking for a way to resolve a promise multiple times. Are there any approaches to make this possible?
想想以下例子:
getPromise() {
const event = new Event('myEvent');
setTimeout(() => {
window.dispatchEvent(event);
}, 5000);
setTimeout(() => {
window.dispatchEvent(event);
}, 7000);
return new Promise((resolve) => {
window.addEventListener('myEvent', () => {
resolve('some value'));
});
resolve('some value'));
});
};
然后.then():
getPromise().then(data => {console.log(data)})
应该给出以下结果:
some value // initial
some value // after 5000ms
some value // after 7000ms
所以我知道有流媒体库数据,但我真的在寻找一种原生的非callbak方法来实现这一目标。
So I know there are libraries to stream data, but I'm really looking for a native non-callbak approach to achieve this.
推荐答案
如何多次解决承诺?
How to resolve a promise multiple times?
你不能。承诺只能解决一次。一旦他们得到解决,他们再也不会改变他们的状态了。它们本质上是单向状态机,具有待处理,已满足和拒绝的三种可能状态。一旦他们从待决到履行或从待决到被拒,他们就无法改变。
You can't. Promises can only be resolved once. Once they have been resolved, they never ever change their state again. They are essentially one-way state machines with three possible states pending, fulfilled and rejected. Once they've gone from pending to fulfilled or from pending to rejected, they cannot be changed.
所以,你几乎不能也不应该使用承诺你想多次出现。事件监听器或观察者比这样的事情的承诺要好得多。您的承诺只会通知您收到的第一个事件。
So, you pretty much cannot and should not be using promises for something that you want to occur multiple times. Event listeners or observers are a much better match than promises for something like that. Your promise will only ever notify you about the first event it receives.
我不知道为什么你在这种情况下试图避免回调。 Promise在 .then()
处理程序中也使用回调。您需要在某处进行回调才能使解决方案正常运行。你能解释为什么你不直接使用 window.addEventListener('myEvent',someCallback)
,因为那样你会做什么吗?
I don't know why you're trying to avoid callbacks in this case. Promises use callbacks too in their .then()
handlers. You will need a callback somewhere to make your solution work. Can you explain why you don't just use window.addEventListener('myEvent', someCallback)
directly since that will do what you want?
您可以返回一个类似承诺的界面(不遵循Promise标准),它会多次调用其通知回调。为了避免与promises混淆,我不会使用 .then()
作为方法名称:
You could return a promise-like interface (that does not follow Promise standards) that does call its notification callbacks more than once. To avoid confusion with promises, I would not use .then()
as the method name:
function getNotifier() {
const event = new Event('myEvent');
setTimeout(() => {
window.dispatchEvent(event);
}, 500);
setTimeout(() => {
window.dispatchEvent(event);
}, 700);
let callbackList = [];
const notifier = {
notify: function(fn) {
callbackList.push(fn);
}
};
window.addEventListener('myEvent', (data) => {
// call all registered callbacks
for (let cb of callbackList) {
cb(data);
}
});
return notifier;
};
// Usage:
getNotifier().notify(data => {console.log(data.type)})
这篇关于如何多次解决承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!