HTML:
<!DOCTYPE html> <html lang="en"> <head> <script type="text/javascript" src="/jquery-2.1.4.js"></script> <script type="text/javascript" src="/index.js" defer></script> <meta charset="UTF-8"> <title></title> </head> <body> <div id="withoutPromise"> <b>Example without promise:<p/></b> </div> <div id="withJqueryPromise"> <b>Example with jQuery promise:<p/></b> </div> <div id="pureJavaScriptPromiseWithoutJquery"> <b>Example with pure JavaScript promise (without jQuery):<p/></b> </div> </body> </html>
JS:
/*global console, $, XMLHttpRequest*/ (function () { "use strict"; function fillResult(id, data) { $.each(data, function (key, val) { $(id).append("key: " + key + "<br/>value: " + val + "<p/>"); }); } function fillPromiseResult(data) { $.each(JSON.parse(data), function (key, val) { $('#pureJavaScriptPromiseWithoutJquery').append("key: " + key + "<br/>value: " + val + "<p/>"); }); } $.getJSON("index.json", function (data) { fillResult("#withoutPromise", data); }); $.getJSON("index.json").done(function (data) { fillResult("#withJqueryPromise", data); }); function makeRequest() { return new Promise(function (resolve, reject) { var myJson = new XMLHttpRequest(); myJson.open("GET", "http://localhost:63342/promiseExample/index.json"); myJson.onload = function () { if (this.status >= 200 && this.status < 300) { resolve(myJson.response); } else { reject(this.statusText); } }; myJson.send(); }); } makeRequest().then(fillPromiseResult, function (errorMsg) { $("#pureJavaScriptPromiseWithoutJquery").append(errorMsg); }).catch(function (err) { console.log("Error: " + err); }); }());
JSON:
{ "first": "first test", "second": "second test", "nested test": [ {"first nest": "nest one"}, {"second nest": "nest two"} ] }
Mostly I was using this example. Notice that it seems that resolve method of promise can accept only one parameter, that is why I needed to create function special for promise. Example download from here.