如何多次解决一个承诺? [英] How to resolve a promise multiple times?

查看:20
本文介绍了如何多次解决一个承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这听起来可能很奇怪,但我正在寻找一种方法来多次解决承诺.有什么方法可以使这成为可能吗?

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

所以我知道有一些库可以传输数据,但我真的在寻找一种原生的非回调方法来实现这一点.

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?

你不能.Promises 只能被解决一次.一旦它们得到解决,它们就永远不会再改变它们的状态.它们本质上是一种单向状态机,具有挂起、完成和拒绝三种可能的状态.一旦它们从待处理变为已完成或从待处理变为拒绝,就无法更改.

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.

因此,您几乎不能也不应该将 Promise 用于您想要多次发生的事情.对于类似的事情,事件侦听器或观察器比 promise 更匹配.您的承诺只会通知您它收到的第一个事件.

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 的接口(不遵循 Promise 标准),它会多次调用其通知回调.为了避免与 Promise 混淆,我不会使用 .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屋!

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