Created
February 8, 2021 17:30
-
-
Save prof3ssorSt3v3/4d9e606a09f5db643c93d0d61a0467bf to your computer and use it in GitHub Desktop.
Code from YouTube video about Error First Callbacks
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
Hey there! | |
Guten Tag. | |
Hur mår du? |
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<title>Document</title> | |
</head> | |
<body> | |
<h1>Error-First Callbacks</h1> | |
<script> | |
function someFunc(someVal, cb) { | |
//sample function that accepts a callback | |
let err = null; | |
if (typeof someVal === 'string') { | |
someVal = someVal.replace('hello', 'Howdy'); | |
} else { | |
err = new TypeError('No string provided'); | |
err.typeProvided = typeof someVal; | |
} | |
cb(err, someVal); | |
} | |
try { | |
someFunc('hello world', (err, response) => { | |
//check first for an error | |
if (err) throw err; | |
console.log('SUCCESS', response); | |
}); | |
someFunc(true, (err, response) => { | |
//check first for an error | |
if (err) throw err; | |
console.log('SUCCESS', response); | |
}); | |
} catch (err) { | |
//handle the error | |
let msg = err.name + '\n' + err.message + '\n'; | |
msg = msg.concat(err.typeProvided, ' sent instead'); | |
console.warn(msg); | |
} | |
</script> | |
</body> | |
</html> |
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
// Error-First callback pattern | |
// Continuation-Passing style: callbacks are continuation functions | |
let fs = require('fs'); | |
fs.readFile('./hello.txt', (err, data) => { | |
//err could be null | |
if (err) return err; | |
//don't run this if err not null | |
console.log(data); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment