Skip to content

Instantly share code, notes, and snippets.

View ufocoder's full-sized avatar
👽
🛸

Sergey ufocoder

👽
🛸
View GitHub Profile
// Проблема #1:
// Этот код вызовет ошибку,
// потому что `handleSuccess` / `handleError` не имеют доступа до `res`
function handleSuccess (data) {
res.writeHead(200, { "Content-Type": "application/octet-stream" }); // *Бум!*
res.write(data);
res.end();
}
function handleError (err) { /* ... */ } // *Бум!*
function rememberX (x) {
return function getX () {
return x;
};
}
// ES6 version might look like the following
// const rememberX = x => () => x;
const get42 = rememberX(42);
function rememberX (x) {
return function getX () {
return x;
};
}
// В ES6 этот же код может быть представлен так:
// const rememberX = x => () => x;
const get42 = rememberX(42);
function multiply (multiplier) {
return function (x) {
return x * multiplier;
};
}
// ES6:
// const multiply = x => y => x * y;
const triple = multiply(3);
function higherOrderNodeCallback (onSuccess, onError) {
function nodeCallback (err, thingIWant) {
if (err) {
onError(err);
} else {
onSuccess(thingIWant);
}
}
return nodeCallback;
}
let x = 96;
get42(); // 42
get36(); // 36
x = 12;
get18(); // 18
x; // 12
readFile(
filePath,
higherOrderNodeCallback(
closeWithContent(res, 200, headers),
closeWithStatus(res, 404)
)
);
function passTest () { /* ... */ }
function failTest () { /* ... */ }
const errorCallback = higherOrderNodeCallback(failTest, passTest);
errorCallback(errorObj, null);
const successCallback = higherOrderNodeCallback(passTest, failTest);
successCallback(null, successObj);
export const doSomething = higherOrderNodeCallback(doA, doB);
import doSomething from "./do-something";
fstat("./some-file", doSomething);
function runAsPromised (task, ...params) {
return new Promise((resolve, reject) =>
task(...params, higherOrderNodeCallback(resolve, reject))
);
}
runAsPromised(readFile, filePath)
.then(convertToContent)
.then(JSON.stringify)
.then(closeWithContent(res, 200, jsonHeaders))