Skip to content

Instantly share code, notes, and snippets.

View JamesTheHacker's full-sized avatar

0xDEADBEEF JamesTheHacker

  • United Kingdom
View GitHub Profile
@JamesTheHacker
JamesTheHacker / wait.js
Last active September 27, 2017 20:59
Supporting file for the following article:
// This function waits for an unknown amount of time
const wait = (delay, callback) => {
// setInterval returns an ID. We need this to stop the timer
const id = setInterval(() => {
// Generate a random number between 0 and 1
const rand = Math.random();
if (rand > 0.95) {
// Call the callback function. Note the first parameter is an error
callback(null, 'Congratulations, you have finished waiting.');
// Calling wait and passing a callback
wait(1000, (err, data) => {
// Did the function return an error?
if (err) throw new Error(err);
// Output the data
console.log(data);
});
node promisify.js
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Waiting ...
Congratulations, you have finished waiting.
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) => { /* … */ };
const util = require('util');
// This function waits for an unknown amount of time
const wait = (delay, callback) => {
// setInterval returns an ID. We need this to stop the timer
const id = setInterval(() => {
// Generate a random number between 0 and 1
const rand = Math.random();
if (rand > 0.95) {
[
"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