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

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: