jessquery
Version:
Modern JavaScript is pretty good, but typing document.querySelector() is a pain. This is a tiny library that makes DOM manipulation easy. jQuery is around 80kb (30kb gzipped), while this is only around 8kb (3.5kb gzipped). Lots of JSDoc comments so it's s
122 lines (108 loc) • 3.59 kB
HTML
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Promisify XHR Example</title>
<style>
#display {
padding: 10px;
border: 1px solid black;
}
</style>
</head>
<body>
<button id="button">Fetch Data</button>
<div id="display"></div>
<script type="module">
import { promisify, $, setErrorHandler } from "../index.js"
// const pollAPIUntilItWorks = async (resolve, reject) => {
// const response = await fetch(
// "https://jsonplaceholder.typicode.com/todos/1"
// )
// console.log("POLLING!!")
// if (response.ok) {
// const data = await response.json()
// resolve(data)
// }
// // No reject, no problem! The error handler will catch it.
// }
// const promisifiedPoll = promisify(pollAPIUntilItWorks, {
// timeout: 3000,
// // You can set the timeout to whatever you want.
// url: "https://someCrappyAPI.com",
// // You can pass extra metadata to the error handler.
// interval: 100,
// // This is mandatory for polling. It's the interval between each attempt.
// })
// $("#button").on("click", async () => {
// $("#display")
// .text("about to poll API")
// .wait(500)
// .do(async (el) => {
// try {
// const data = await promisifiedPoll()
// el.text(JSON.stringify(data))
// } catch (error) {
// console.log(error)
// }
// })
// })
// const promisifiedDogURL = promisify(
// async (resolve, reject) => {
// const response = await fetch(
// "https://dog.ceo/api/breeds/image/random"
// )
// if (response.ok) {
// const data = await response.json()
// resolve(data.message)
// } else {
// reject(`Error: ${response.status}`)
// }
// },
// {
// timeout: 3000,
// url: "https://dog.ceo/api/breeds/image/random",
// interval: 100,
// }
// )
// $("#button").on("click", async () => {
// $("#display")
// .text("about to fetch dog")
// .wait(500)
// .html(`<img />`, true)
// .set("src", promisifiedDogURL())
// })
const intervalFunction = async (resolve, reject) => {
// const response = await fetch("http://localhost:3000?delay=2000", {
// method: "POST",
// })
// if (response.ok) {
// const data = await response.text()
// resolve(data)
// } else {
// reject(`Error: ${response.status}`)
// }
// }
console.log("POLLING!!")
}
const promisifiedInterval = promisify(intervalFunction, {
timeout: 3000,
interval: 100,
})
$("#button").on("click", async () => {
$("#display")
.text("about to fetch data")
.wait(500)
.do(async (el) => {
try {
const data = await promisifiedInterval()
el.text(JSON.stringify(data))
} catch (error) {
console.log(error)
}
})
})
</script>
</body>
</html>