Skip to content

Instantly share code, notes, and snippets.

@nalmeida
Last active November 4, 2022 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nalmeida/30f01f7d150ae763492abe5ea64e267d to your computer and use it in GitHub Desktop.
Save nalmeida/30f01f7d150ae763492abe5ea64e267d to your computer and use it in GitHub Desktop.
Node / JS
// from: https://medium.com/backticks-tildes/understanding-method-chaining-in-javascript-647a9004bd4f
class Arithmetic {
constructor() {
this.value = 0;
}
sum(...args) {
this.value = args.reduce((sum, current) => sum + current, 0);
return this;
}
add(value) {
this.value = this.value + value;
return this;
}
subtract(value) {
this.value = this.value - value;
return this;
}
average(...args) {
this.value = args.length
? (this.sum(...args).value) / args.length
: undefined;
return this;
}
}
a = new Arithmetic()
a.sum(1, 3, 6) // => { value: 10 }
.subtract(3) // => { value: 7 }
.add(4) // => { value: 11 }
.value // => 11
// Console Output
// 11
// from: https://stackoverflow.com/questions/49033694/how-to-use-then-in-node-js
// video: https://www.youtube.com/watch?v=_JOP8rcDjJE
// video pt-BR: https://www.youtube.com/watch?v=7Bs4-rqbCQc
function one(){
return new Promise(resolve => {
setTimeout(() => {
resolve('one');
}, 1000);
});
}
function two(){
return new Promise(resolve => {
setTimeout(() => {
resolve('two');
}, 1000);
});
}
function three(){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('three');
// reject(new Error('three'));
}, 1000);
});
}
one()
.then((msg) => {
console.log('first msg:', msg);
return two();
})
.then((msg) => {
console.log('second msg:', msg);
return three();
})
.then((msg) => {
console.log('third msg:', msg);
})
.catch((error) => {
console.error('Something bad happened:', error.toString());
});
// OR
async function run() {
await one();
await two();
three();
}
run();
// from: https://lavrton.com/javascript-loops-how-to-handle-async-await-6252dd3c795/
function delay() {
return new Promise(resolve => setTimeout(resolve, 300));
}
async function delayedLog(item) {
// notice that we can await a function
// that returns a promise
await delay();
console.log(item);
}
async function processArray(array) {
for (const item of array) {
await delayedLog(item);
}
console.log('Done!');
}
processArray([1, 2, 3]);
const UUID = Math.random().toString(36).slice(-8);
@nalmeida
Copy link
Author

nalmeida commented Sep 2, 2022

Good Video about Promises: https://www.youtube.com/watch?v=52JDIMoTTzI

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment