In Javascript I would probably do... the same thing? But I would do it using promises?
In Javascript I would probably do... the same thing? But I would do it using promises?
// using Promise.race so whoever finishes first wins
var fetchingWithTimeout = Promise.race([
// first promise: actually try to perform the computation
fetching,
// second promise: wait x seconds, then reject
Promise.delay(x*1000).then(Promise.reject('Timed out')),
]);
You can apply the timeout wherever you want (or apply different timeouts in different corners of the app) without throwing out the raw promise to perform the computation no matter the time cost.In cases like a node.js server, Promises allow a single node instance to handle thousands of concurrent requests because the event loop isn't blocking waiting for a single IO request to complete, the process can happily do lots of other things while Promises are pending.
So it's right that promises allow me to do the same thing I would do with sequential code in other languages? If I had the option of using coroutines when would I choose to use promises?
Edit: I'm asking because the context of this thread is that one person said that sequential APIs for asynchronous operations, such as open(2), are pretty nice, and someone else said no they're not pretty nice and we should explicitly deal with the asynchronous nature of operations like open(2) by NOT writing sequential code there.
If you don't have either, then you'll probably end up re-implementing one or the other eventually anyway.