A Promise is the eventual result of an asynchronous operation, just like giving someone a promise. Promises help handle errors, which results in writing cleaner code without callbacks. Instead of passing in an additional function that takes an error and result as parameters to every function, you can simply call your function with its parameter and get a Promise:
getUserinfo('leo', function(err, user){ if (err) { // handle error onFail(err); return; } onSuccess(user); });
versus
var promiseUserInfo = getUserinfo('leo'); promiseUserInfo.then(function(user) { onSuccess(user); }); promiseUserInfo.catch(function(error) { // code to handle error onFail(user); });
The benefit of using Promises isn't obvious if there is only one async operation. If there are many async operations with one depending on another, the callback pattern will quickly turn into a deeply nested structure, while Promises can keep your code shallow and easier to read.
Promises can...