Last active
March 24, 2021 19:52
-
-
Save gm50x/5c460b67acfe5feef57e0e5bd7cc5173 to your computer and use it in GitHub Desktop.
Callbacks X Promissified
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
const http = require('http') | |
const baseApiUrl = 'http://jsonplaceholder.typicode.com' | |
// using error-back pattern --> or anti-pattern :) | |
const fetchDataWithPromise = () => { | |
return new Promise((resolve, reject) => { | |
http.get(`${baseApiUrl}/posts`, res => { | |
let rawData = ''; | |
res.on('data', chunk => rawData += chunk) | |
res.on('end', () => { | |
const data = JSON.parse(rawData); | |
// when things are done, we resolve the promise | |
resolve(data) | |
}) | |
res.on('error', err => { | |
console.log('----- ERR -----\n', err.message) | |
// if things went south we can reject the promise | |
reject(err) | |
}) | |
}).end() | |
}) | |
} | |
const main = async () => { | |
try { | |
const data = await fetchDataWithPromise() | |
console.log(data) | |
} catch (err) { | |
console.log(err) | |
} | |
} | |
main() |
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
const http = require('http') | |
const baseApiUrl = 'http://jsonplaceholder.typicode.com' | |
// using error-back pattern --> or anti-pattern :) | |
const fetchDataWithCallback = (callback) => { | |
http.get(`${baseApiUrl}/posts`, res => { | |
let rawData = ''; | |
res.on('data', chunk => rawData += chunk) | |
res.on('end', () => { | |
const data = JSON.parse(rawData); | |
// when things are done, we execute the callback function | |
callback(null, data) | |
}) | |
res.on('error', err => { | |
console.log('----- ERR -----\n', err.message) | |
callback(err, null) | |
}) | |
}).end() | |
} | |
const main = async () => { | |
const printDataAfterFetching = (err, data) => { | |
if (!err) { | |
console.log(data) | |
} else { | |
console.log(err) | |
} | |
} | |
fetchDataWithCallback(printDataAfterFetching) | |
} | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment