Hacker News new | past | comments | ask | show | jobs | submit login

Correct but once you get some functions returning promises and other functions returning actual values then your own code base can become confusing. I constantly find myself in these types of code bases trying to find function definitions so I know what it returns.

You can try and make 100% of your asynchronous methods return promises but what happens when you need to work with a library that can't use promises? Do you write a callback for that? Now you have a mixture and sure a few of these no big deal but when the code base balloons and you start having one offs all over the place now you need to figure out what returns what and code specifically to that.

Maybe if promises were in ECMAScript from the beginning then everyone would have used them and it wouldn't be a huge deal but right now it can get a bit frustrating, in my opinion. The stack traces of these nested promises are never fun to dive into as well though that likely depends on whether you're using a polyfill or not.




I'm not quite sure I understand you, but it sounds like a case for `Promise.resolve(value)`[1] – that's what I do whenever I don't know if something will be a Promise or an already-resolved value. `Promise.resolve(value)` returns a Promise that immediately resolves with `value` or whatever `value` resolves to if it's a Promise – no need to do any checks yourself, no need to nest Promises inside Promises inside Promises.

For example, imagine you have a charting library and you want to draw a chart, but you don't know if the data is available already or if it's being loaded asynchronously. You can just write:

    // `drawChart(data)` is a synchronous function
    // `data` may be the data itself or a promise that resolves to the data
    Promise.resolve(data).then(drawChart)
For me, this is actually the killer feature of Promises, avoiding callback hell is just a nice side-effect. Once you start thinking of Promises as placeholders for values that may or may not be known already (rather than just an abstraction of the `callback(err, value)` pattern), you can write some really elegant code.

[1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...


Fair enough that would take care of my issue for the most part. Native implementations of promises should work well with that. Seems most of the polyfills end up using setTimeout() which is kinda slow[1] and one of the reasons I don't typically like working with them (waiting for more ubiquitous support).

Thanks for the info!

[1] http://www.krissiegel.com/rants/2015/11/7/settimeout-sucks




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: