JavaScript Promise

Tagged as:

Update 1: Thanks to fadzlan for fixing the second example.

This is an answer to a question in FB group:-

Confuse with callback and promises. In $.ajax, the success callback is async by default, why do we need to use promise? Can someone good in JS explain?

Promise let you program in async while maintaining the synchronize structure of your code. Take this code:-

var res;
db_connect(host, function(conn) {
  res = conn.query("SELECT * FROM ...");
});
console.log(res); // probably still null

Using promise:-

var res;
db.connect(host).then(function(conn) {
  res = conn.query("select * from ...");
  return res;
}).then(function(res){
  console.log(res); // already available
});

The first code is a common mistake to someone new in async programming because while the code is async, the structure is not, you assume it to run from top to bottom. Using promise, the program definitely run from top to bottom as you read it.

But promises like a callback? that then() is a callback of db.connect, but why promises is not a callback? What’s the difference ?

Ok, let rephrase it. Promise is a different (or maybe better) way of using callback. So doesn’t mean that when you use promise, you’re not using callback anymore. You can’t remove callback since it’s the core of the language, that’s how javascript work. But you can use it in different way.

For more in-depth write up on promise, I’d suggest to read this article (a very long one, /me haven’t finished it yet ;))

Written on December 7, 2015 by kamal
About author

Lead Engineer at Xoxzo Inc. Develop web applications in Python/Django. Interested in open source and tech talent development.

Xoxzo.com provide API services for developer to develop messaging and voice based application. The postings on this site are my own and don't necessarily represent my employer's positions, strategies or opinions. I can be reached via Twitter @k4ml.

Ikuti perkembangan terkini melalui twitter kami @koditi atau FB Page fb.me/koditi.