Created
September 28, 2020 19:33
-
-
Save FredrikOseberg/c3ff4193ab52347c01cebb23af318bfb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fetch = (url, options) => { | |
// simplified | |
return new Promise((resolve, reject) => { | |
const xhr = new XMLHttpRequest() | |
// ... make request | |
xhr.onload = () => { | |
const options = { | |
status: xhr.status, | |
statusText: xhr.statusText | |
... | |
} | |
resolve(new Response(xhr.response, options)) | |
} | |
xhr.onerror = () => { | |
reject(new TypeError("Request failed")) | |
} | |
} | |
fetch("https://swapi.dev/api/people/1") | |
// Register handleResponse to run when promise resolves | |
.then(handleResponse) | |
.catch(handleError) | |
// conceptually, the promise looks like this now: | |
// { status: "pending", onsuccess: [handleResponse], onfailure: [handleError] } | |
const handleResponse = (response) => { | |
// handleResponse will automatically receive the response, ¨ | |
// because the promise resolves with a value and automatically injects into the function | |
console.log(response) | |
} | |
const handleError = (response) => { | |
// handleError will automatically receive the error, ¨ | |
// because the promise resolves with a value and automatically injects into the function | |
console.log(response) | |
} | |
// the promise will either resolve or reject causing it to run all of the registered functions in the respective arrays | |
// injecting the value. Let's inspect the happy path: | |
// 1. XHR event listener fires | |
// 2. If the request was successfull, the onload event listener triggers | |
// 3. The onload fires the resolve(VALUE) function with given value | |
// 4. Resolve triggers and schedules the functions registered with .then | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment