Skip to content

Instantly share code, notes, and snippets.

View JamesTheHacker's full-sized avatar

0xDEADBEEF JamesTheHacker

  • United Kingdom
View GitHub Profile
node promisify.js
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Waiting ...
const util = require('util');
// Here we use util.promisify to convert the function to a promise
const waitAsync = util.promisify(wait);
//And here we use the promisified function. Cool huh?
waitAsync(1000)
.then(data => console.log(data))
.catch(err => console.error(`[Error]: ${err}`));
const wait = (delay, callback) => { /* … */ };
[
"nodejs ",
[
[
"\u003cb\u003enode js\u003c\/b\u003e \u003cb\u003etutorial\u003c\/b\u003e",
0,
[
10
],
{
const state = {
twitter: '@JamesJefferyUK',
tweets: [
{
tweet: 'I <3 JavaScript',
read: false
},
{
tweet: 'React is so cooool',
read: false
// This is how you shallow clone an object
const shallowClone = Object.assign({}, state);
// Change the twitter handle
shallowClone.twitter = '@zuck';
// Origional state isn't changed
console.log(state.twitter); // @JamesJefferyUK
// Changed
// Change the tweet on our clone
shallowClone.tweets[3].tweet = 'Hijacking your tweets bruh!';
// Changed :)
console.log(shallowClone.tweets[3]);
// Noooooo! Also change!
console.log(state.tweets[3]);
// Both properties reference the same object
// Deep clone an object
const deepClone = JSON.parse(JSON.stringify(state));
deepClone.tweets[3].tweet = 'Hijacking your tweets bruh!';
// Origional tweet is unchanged
console.log(state.tweets[3].tweet);
// Cloned tweet is changed
console.log(deepClone.tweets[3].tweet);
const deepFreeze = o => Object
.getOwnPropertyNames(o)
.forEach(n=> {
if (typeof o[n] == 'object' && o[n] !== null)
deepFreeze(o[n]);
return Object.freeze(o);
});
// Shallow freeze
Object.freeze(state);
// This will not work
state.twitter = '@zuck';
// Look, it's still @JamesJefferyUK
console.log(state.twitter);
// But this works because we're modifying a reference value (an object)