0

Let a promise p implementing a time-based logic similar to an HTTP request, ie. if it is pending for less than 5 seconds and a result has been acquired then resolve otherwise reject with a timeout. I want to use it as a wrapper in an event, so whether anything comes in or not, the promise should be settled anyway. Although the following snippet seems to work, I am not sure that it is implemented correctly:

let p = new Promise(function(resolve, reject) {
    evt.on('dataStream', stream => {
      if(stream.payload) {
        let payload = stream.payload;
        resolve(stream)
      }
    })
    setTimeout( () => {
      reject('Timeout!')
    }, 5000)
});

p.then(res => console.log(res))
 .catch(err => console.log(err))
fool-dev
  • 7,671
  • 9
  • 40
  • 54
jeremyTob
  • 131
  • 10

1 Answers1

0

Although the following snippet seems to work, I am not sure that it is implemented correctly:

I agree your snippet is right.

In addition, if your event is promise, I've found a similar way.

// Rough implementation. Untested.
function timeout(ms, promise) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      reject(new Error("timeout"))
    }, ms)
    promise.then(resolve, reject)
  })
}

timeout(1000, event).then(function(stream) {
  // process stream
}).catch(function(error) {
  // might be a timeout error
})

From Fetch API request timeout?

noymer
  • 240
  • 1
  • 11