Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gm50x/5c460b67acfe5feef57e0e5bd7cc5173 to your computer and use it in GitHub Desktop.
Save gm50x/5c460b67acfe5feef57e0e5bd7cc5173 to your computer and use it in GitHub Desktop.
Callbacks X Promissified
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()
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