Created
May 22, 2023 23:40
-
-
Save AlexcastroDev/cbfd438ef79fb708f31e59cc3bbc42df to your computer and use it in GitHub Desktop.
Closure
This file contains 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
function closureRequest() { | |
let success = false, error = false, data = null; | |
const dispatch = async (fn) => { | |
try { | |
data = await fn(); | |
success = true; | |
error = false; | |
} catch { | |
success = false; | |
error = true; | |
} | |
}; | |
const getSuccess = () => success; | |
const getError = () => error; | |
const getData = () => data; | |
const getDispatch = () => dispatch; | |
return { | |
getSuccess, | |
getError, | |
getData, | |
data, | |
getDispatch, | |
}; | |
} | |
const closure = closureRequest() | |
const { getDispatch, getData } = closure | |
const dispatch = getDispatch() | |
await dispatch(async () => { | |
return await fetch('https://swapi.dev/api/people/1').then(res => res.json()) | |
}) | |
console.log(getData()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment