6 ms·
Ask HN: What are Promises?
I have been writing JavaScript for 10 years (admittedly, it was very jQuery in the early years) but can't seem to understand Promises. Every tutorial I read about it assumes I get its amazingly powerful need. I just can't freaking understand. Can you recommend a simple tutorial which explains it with examples of real-life problems?
- franciscop 10y agoI can just explain it with my own words. Promises are a different way of doing callback/asynchronous work. So traditionally, you would do this in JS: API.get('/cars', function(cars){ // Here you have your car list }); The main problem with this is that each library would define their own callback response parameters. We could return `cars` as a variable (jQuery), or we could return two parameters such as `(error, cars)` as in Node.js, etc. So promises standardizes the way that different libraries execute Asynchronous code. Instead of whatever you want, you'd have to follow this syntax to do the same as above: API.get('/cars').then(function(cars){ // Here you have your cars }); Then if you are the one actually creating the promises it gets more tricky; let me know if you just want to use libraries with promises (above) or you want to write your own promises so I can expand the answer.