Skip to content

Instantly share code, notes, and snippets.

View aherve's full-sized avatar

Aurélien aherve

View GitHub Profile
asyncGreet () {
this.someThingAsync()
.then(this.greet.bind(this))
}
class Foo {
constructor (name) {
this.name = name
}
greet () {
console.log('hello, this is ', this.name)
}
someThingAsync () {
const Greeters = []
for (var i = 0 ; i < 10 ; i++) {
Greeters.push(function () { return console.log(i) })
}
Greeters[0]() // 10
Greeters[1]() // 10
Greeters[2]() // 10
@aherve
aherve / typeof.js
Last active December 13, 2016 11:16
typeof {} === 'object' // true
typeof 'a' === 'string' // true
typeof 1 === number // true
// But....
typeof [] === 'object' // true
// These are ok
'abc' === 'abc' // true
1 === 1 // true
// These are not
[1,2,3] === [1,2,3] // false
{a: 1} === {a: 1} // false
{} === {} // false
@aherve
aherve / replace.js
Last active December 13, 2016 11:06
let s = "bob"
const replaced = s.replace('b', 'l')
replaced === "lob" // first match only
s === "bob" // original string is remained unchanged
function demoPromise (userId) {
return User
.findById(userId)
.then(user => Promise.all([user, doSomethingAsync(user)]))
.then(([user, result]) => finalResult(user, result));
}
@aherve
aherve / parallel.ts
Last active December 8, 2016 02:21
import {sleep} from 'previousExample'
async function slowDouble (i): Promise<number> {
await sleep(1000) // non-blocking
return 2 * i
}
async function main () {
// slowDouble is async, therefore it returns a promise
const result = await Promise.all([1, 2, 3].map(slowDouble))
function sleep (ms: number) {
return new Promise(resolve => {
setTimeout(resolve, ms)
})
}
async function main () {
console.log('hello')
await sleep(1000) // non-blocking
console.log('good bye')
@aherve
aherve / throw.ts
Last active December 7, 2016 13:36
// ----- Old school Promise-style ----- //
function nope (): Promise<never> {
return Promise.reject('lol no')
}
// ----- Hipster async way ----- //
async function asyncNope (): Promise<never> {
throw 'lol no'
}