Skip to content

Instantly share code, notes, and snippets.

// making an HTTP request using Fetch API
const aThing = fetch('http://restcountries.eu/rest/v2/all', {})
.then( (response) => { // THEN 1
// fetch returns fulfilled Promise even if
// the server responds with an error - check the status
if (response.status === 200) {
return response.json()
} else {
throw Error('Something went wrong ;(')
// This corresponds to promiseExecutor
promExec = function ( successCb, failureCb ) {
setTimeout( () => { // run when stack is clear
if (1) successCb('Promise resolved', then2successCb) // called if things went well
else failureCb('Promise rejected') // called if things went bad
}, 0)
}
// THEN 1
const then1successCb = function ( resolveMessage, successCb ) { // SUCCESS Handler
//=============================================================================
// Executor function is called right away when a promise is created
// Start async process here
// (HTTP requests, storing data to a database etc.)
// EXECUTOR 1------------------------------------------------------------------
const promiseExecutor1 = (resolve, reject) => {
console.log('Strating 1st async operation (promiseExecutor1)')
setTimeout( () => { // start 1st async task
console.log('\n1st async operation DONE')
if (1) resolve('Promise 1 resolved') // called if things went well
@VYV7
VYV7 / XMLHttpRequest.js
Last active May 28, 2020 07:12
Basic example of XMLHttpRequest
// making an HTTP request
// create instance of the request and initialise it
const myRequest = new XMLHttpRequest()
console.log('New request object:') // DEBUG
console.log(myRequest) // DEBUG (comment out sent())
// onload event (handles the response if readyState is DONE)
myRequest.onload = () => {
@VYV7
VYV7 / XMLHttpRequest.js
Last active May 27, 2020 09:34
Basic example of XMLHttpRequest
// making an HTTP request
// create instance of the request
const myRequest = new XMLHttpRequest()
console.log('New XMLHttpRequest object:') // DEBUG
console.log(myRequest) // DEBUG (comment out sent())
// onload event (handles the response if readyState is DONE)
myRequest.onload = () => {
//---------------------------------------------------------
// define what to do when the promise is resolved/rejected
// Promise.then( onFulfilled(), onRejected() ).catch()
let message
myPromise
.then( (resolveMessage) => {
message = `Then1: ${resolveMessage}`
console.log('\n' + message)
console.log(myPromise)
@VYV7
VYV7 / PromiseDeclaration.js
Last active June 23, 2023 11:40
Creating a Promise
//---------------------------------------------------------
// Executor function is called right away when a promise is created
// Start a long running process here
// (HTTP requests, storing data to a database etc.)
const promiseExecutor = (resolve, reject) => {
setTimeout( () => {
if (1) {
resolve('Promise resolved') // called if things went well
} else {
reject('Promise rejected') // called if things went bad