Skip to content

Instantly share code, notes, and snippets.

@Kcko
Created May 11, 2024 12:45
Show Gist options
  • Save Kcko/6cdb7e3c138438e19da3b930ac77ab0d to your computer and use it in GitHub Desktop.
Save Kcko/6cdb7e3c138438e19da3b930ac77ab0d to your computer and use it in GitHub Desktop.
// Destructure into multiple variables
const obj = { val: 1 };
const { val: a, val: b, val } = obj;
console.log(a); // -> 1
console.log(b); // -> 1
console.log(val); // ->
// Chaining catch in Promise
const somePromise = async () => Promise.reject('error');
somePromise()
.then(e => {
//
})
.catch(e => {
throw new Error('error happened');
})
.catch(e => {
console.log('hi ' + e); // hi Error
});
// Multiple handlers for Promise
async function add(a, b) {
return a + b;
}
const promise = add(1, 2);
promise.then(e => `Result 1: ${e}`);
promise.then(e => `Result 2: ${e}`);
// -> Result 1: 3
// -> Result 2: 3
// Mixed promise handler liky try catch
async function someFunction() {
const res = await somePromise().catch(err => {
/* handle */
});
}
// Advanced default params
function test({ val = -1 } = {}) {
console.log(val);
}
test(); // -> -1
test({}); // -> -1
test({ val: 123 }); // -> 12
// Generate compact numbers
const formatter = Intl.NumberFormat('en',{ notation: 'compact' });
formatter.format('123'); // -> 123
formatter.format('1234'); // -> 1.2K
formatter.format('1235678'); // -> 1.2M
formatter.format('1235678901'); // -> 1.2B
//Default parameters previously declared
function test(x, y, z = x + y) {
console.log(z);
}
test(1, 1, 1); // -> 1
test(1, 1); // -> 2
// Additional arguments to setTimeout()
function callback(value) {
console.log(value);
}
setTimeout(callback, 1000, 5);
// -> Prints '5' after 1 second
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment