Javascript ECMAScript 2015 - Part 10: Promises

written by Andreas Schipplock
In ecmascript 2015 you can make use of "promises". This feature is already available for quite some time in modern webbrowsers but now with ecmascript 2015 you can start to count on it.

Promises are like callbacks but with better syntax and better error handling. It's really just that.

In the following example I'm pretending to upload imaginary pictures ;). The "upload" function will be asynchronous but when I call it, you will notice that it looks synchronous. As I said, it's just a better way to use callbacks; a much cleaner way if you ask me. It's easier to read.
00001: function upload(pictureName = '') {
00002:   console.log('uploading: ' + pictureName);
00003:   let url = 'https://httpbin.org/delay/3';
00004:   // just for the demo to show off the .catch
00005:   if (pictureName == 'picture4.jpeg') {
00006:     // that url isn't available
00007:     url = 'https://httppbin.org/delay/3';
00008:   }
00009:   return new Promise((resolve, reject) => {
00010:     let req = new XMLHttpRequest();
00011:     req.open('GET', url);
00012:     req.onload = () => {
00013:       if (req.status == 200) {
00014:         resolve(pictureName);
00015:       } else {
00016:         reject(Error(req.statusText));
00017:       }
00018:     };
00019:     req.onerror = () => {
00020:       reject(Error('request failed for: ' + pictureName));
00021:     };
00022:     req.send();
00023:   });
00024: }
00025: 
00026: // let's begin with an immediately invoked function expression
00027: (() => {
00028:   // define some pictures
00029:   let pictures = [
00030:     'picture1.jpeg',
00031:     'picture2.jpeg',
00032:     'picture3.jpeg',
00033:     'picture4.jpeg',
00034:     'picture5.jpeg'
00035:   ];
00036: 
00037:   for (let picture of pictures) {
00038:     upload(picture)
00039:       .then((response) => {
00040:         console.log('uploaded: ' + response);
00041:       })
00042:       .catch((error) => {
00043:         console.log(error);
00044:       });
00045:   }
00046: })();
I get the following output:
uploading: picture1.jpeg
uploading: picture2.jpeg
uploading: picture3.jpeg
uploading: picture4.jpeg
uploading: picture5.jpeg
Error: request failed for: picture4.jpeg(…)
uploaded: picture1.jpeg
uploaded: picture2.jpeg
uploaded: picture5.jpeg
uploaded: picture3.jpeg
The calls to upload the "file" are in order (as expected) and the "then" part isn't in order and that's expected as well. It's async but in the implementation it's all in one place. You can make a much better guess about what happens here.

IMHO this is very easy to read, easy to guess what happens and "is nice" :P.