Skip to content

Instantly share code, notes, and snippets.

@swashata
Created September 13, 2019 05:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swashata/bd80852309d3119fbf29c267448af9c1 to your computer and use it in GitHub Desktop.
Save swashata/bd80852309d3119fbf29c267448af9c1 to your computer and use it in GitHub Desktop.
Promises - The Easy Way
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="fetch">Start the fetch</button>
<button id="timeout">Start the Timeout</button>
<button id="promise-button">Promise Me</button>
<script src="./script.js" type="text/javascript"></script>
</body>
</html>
'use strict';
function fetchThing() {
const url = 'https://api.github.com/users/swashata';
const response = fetch(url);
console.log('response', response);
response
.then(data => {
console.log('data', data);
return data.json();
})
.then(value => {
return value.blog;
})
.then(value => {
throw new Error('Custom error');
console.log(value);
})
.catch(e => {
console.log(e);
});
}
document.querySelector('#fetch').addEventListener('click', fetchThing);
function doSomethingAfterTimeout() {
setTimeout(() => {
console.log('1 sec passed');
}, 1000);
}
function doSomethingWithPromise() {
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('1 sec has passed');
}, 1000);
});
myPromise.then(value => {
console.log(value);
console.log('done');
});
}
document
.querySelector('#timeout')
.addEventListener('click', doSomethingWithPromise);
// const promiseButton = document.querySelector('#promise-button');
// let hasClicked = false;
// function handler() {
// hasClicked = true;
// console.log('Passed');
// }
// promiseButton.addEventListener('click', handler);
// setTimeout(() => {
// if (hasClicked === false) {
// promiseButton.removeEventListener('click', handler);
// console.log('Failed');
// }
// }, 5000);
const promiseMeButton = new Promise((resolve, reject) => {
const promiseButton = document.querySelector('#promise-button');
const handler = () => {
resolve('the user has clicked the button');
};
promiseButton.addEventListener('click', handler);
setTimeout(() => {
reject('the user has not clicked the button');
}, 5000);
});
promiseMeButton
.then(val => {
console.log(val);
})
.catch(err => {
console.error(err);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment