Skip to content

Instantly share code, notes, and snippets.

@mikedll
Created April 1, 2019 14:48
Show Gist options
  • Save mikedll/0e660029f68fd31be55d3ee6f4a6519f to your computer and use it in GitHub Desktop.
Save mikedll/0e660029f68fd31be55d3ee6f4a6519f to your computer and use it in GitHub Desktop.
Promises exercise
{
"id": 1,
"name": "Michael",
"lastname": "Rivers"
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.js"></script>
<script language="javascript" src="index.js" ></script>
</head>
<body>
<div class="main"></div>
</body>
</html>
const wait = ms => new Promise(resolve => setTimeout(resolve, ms))
function log(s) {
$('.main').append($('<div class="message">' + s + '</div>'))
}
const doGet = (url) => new Promise((resolve, reject) => {
$.ajax({
url: url,
dataType: 'JSON',
success: function(data) { return resolve(data) },
error: function() { return reject() }
})
})
async function runMore() {
var result = await doGet('file.json')
log(result.lastname)
}
$(function() {
// const p = Promise.resolved
// p.then(result => runMore())
new Promise((resolve, reject) => {
log("Initial");
resolve("something interesting");
})
.then((result) => {
log("Second: " + result);
})
.then(_ => {
log("third log msg.")
})
.catch(_ => {
log("error occurred.")
})
.then(_ => log("no matter what."))
wait(1000)
.then(_ => {
log("Interesting post.")
})
.then(_ => wait(2000))
.then(_ => log("another interesting post."))
wait(1000)
.then(_ => {
doGet('NOT_ON_SERVER.json')
.then(data => log("got very interesting json: " + data.name))
.catch(_ => log("unable to find anything."))
})
runMore()
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment