Skip to content

Commit

Permalink
Diberry/intro code updates 2 (#39)
Browse files Browse the repository at this point in the history
* support modules

* update code
  • Loading branch information
diberry authored Nov 6, 2023
1 parent 3b20d3b commit 8e3dcb7
Show file tree
Hide file tree
Showing 6 changed files with 1,453 additions and 11 deletions.
12 changes: 10 additions & 2 deletions nodejs-intro/.eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,21 @@
"node": true
},
"extends": "eslint:recommended",
"parser": "@babel/eslint-parser",
"parserOptions": {
"ecmaVersion": "latest"
"ecmaVersion": "latest",
"requireConfigFile": false,
"babelOptions": {
"parserOpts": {
"plugins": ["topLevelAwait"]
}
}
},
"rules": {
"no-console": "off",
"no-undef": "off",
"no-unused-vars": "off",
"no-shadow": "off"
"no-shadow": "off",
"require-await": "error"
}
}
16 changes: 16 additions & 0 deletions nodejs-intro/3-how-nodejs-works/async-await-top-level.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// top-level async/await asynchronous example

const fs = require('fs').promises;

const filePath = './file.txt';

// `async` before the parent function
try {
// `await` before the async method
const data = await fs.readFile(filePath, 'utf-8');
console.log(data);
console.log('Done!');
} catch (error) {
console.log('An error occurred...: ', error);
}
console.log("I'm the last line of the file!");
24 changes: 24 additions & 0 deletions nodejs-intro/3-how-nodejs-works/promise-create-basic.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Create a basic promise function
function promiseFunction() {
return new Promise((resolve, reject) => {

// do something

if(error){
// indicate success
reject(error)
} else {
// indicate error
resolve(data)
}
})
}

// Call a basic promise function
promiseFunction()
.then((data) => {
// handle success
})
.catch((error) => {
// handle error
})
17 changes: 9 additions & 8 deletions nodejs-intro/3-how-nodejs-works/promises.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
// promises asynchronous example

const fs = require('fs').promises;

const filePath = './file.txt';

// request to read a file
fs.readFile(filePath, 'utf-8')
.then((data) => {
console.log(data);
console.log('Done!');
})
.catch((error) => {
console.log('An error occurred...: ', error);
});
.then((data) => {
console.log(data);
console.log('Done!');
})
.catch((error) => {
console.log('An error occurred...: ', error);
});

console.log(`I'm the last line of the file!`)
Loading

0 comments on commit 8e3dcb7

Please sign in to comment.