Looking into JavaScript promises; what they are and how to implement them.
Essentially it’s a procedure which results in a call being either a success or an error.
let myPromise = new Promise(function(myResolve, myReject) {
let request = new XHLHttpRequest()
request.open('GET', data.htm")
request.onload = function() {
if(request.status == 200) {
myResolve(request.response)
} else {
myReject("Not found)
}
}
request.send()
})
myPromise.then(
function(value) {
myDisplay(value)
}
function(error) {
myDisplay (error)
}
)
try {
const data = getJSONSync(data.json);
const pieceOfData = getJSONSync(data.moreData[0]);
addHtmlToPage(pieceOfData.html);
} catch (e) {
addTextToPage("Failed to show data");
}
document.querSelector(".example").style.display = "none";
let myPromise = new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("Hello");
}, 3000);
});
myPromise.then(function (value) {
document.getElementById("example").innerHTML = value;
});
asyncThing1()
.then(function () {
return asyncThing2();
})
.then(function () {
return asyncThing3();
})
.catch(function (err) {
return asyncRecovery1();
})
.then(
function () {
return asyncThing4();
},
function (err) {
return asyncRecovery2();
}
)
.catch(function (err) {
console.log("Caught it");
})
.then(function () {
console.log("Finished!");
});