Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
167 views
in Technique[技术] by (71.8m points)

javascript - 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?

Think of the following example:

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'));
  });
};

And then .then():

getPromise().then(data => {console.log(data)})

Should give the following result:

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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?


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)})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...