Skip to content

Instantly share code, notes, and snippets.

View Gaafar's full-sized avatar

Gafi (Mostafa Gaafar) Gaafar

View GitHub Profile
@Gaafar
Gaafar / dot-function.md
Last active July 24, 2017 04:49
dot-function

Motivation

Easy access for a property in higher order functions, enables composition & piping

Examples

const strings = ["", "a"]
const filteredStrings = strings.filter(.length) // ["a"]
// this will not work in top level
// await makeRequest()
// this will work
makeRequest().then((result) => {
// do something
})
const makeRequest = async () => {
await callAPromise()
await callAPromise()
await callAPromise()
await callAPromise()
await callAPromise()
throw new Error("oops");
}
makeRequest()
const makeRequest = () => {
return callAPromise()
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => callAPromise())
.then(() => {
throw new Error("oops");
})
}
const makeRequest = async () => {
const value1 = await promise1()
const value2 = await promise2(value1)
return promise3(value1, value2)
}
const makeRequest = () => {
return promise1()
.then(value1 => {
// do something
return Promise.all([value1, promise2(value1)])
})
.then(([value1, value2]) => {
// do something
return promise3(value1, value2)
})
const makeRequest = () => {
return promise1()
.then(value1 => {
// do something
return promise2(value1)
.then(value2 => {
// do something
return promise3(value1, value2)
})
})
const makeRequest = async () => {
const data = await getJSON()
if (data.needsAnotherRequest) {
const moreData = await makeAnotherRequest(data)
console.log(moreData)
return moreData
} else {
console.log(data)
return data
}
const makeRequest = () => {
return getJSON()
.then(data => {
if (data.needsAnotherRequest) {
return makeAnotherRequest(data)
.then(moreData => {
console.log(moreData)
return moreData
})
} else {
const makeRequest = async () => {
try {
// this parse may fail
const data = JSON.parse(await getJSON())
console.log(data)
} catch (err) {
console.log(err)
}
}