Julian Tölle
Developer @
narando &
TrackCode
Backend Development & Devops
Javascript for 13 months
Node.js and JavaScript are:
import fs from "fs";
fs.readFile("config.txt", (err, config) => {
if(err) {
console.error(err);
return;
}
console.log(config);
});
console.log("Hello World!");
var p_client = new Db("integration_tests_20");
p_client.open((err, p_client) => {
p_client.dropDatabase((err, done) => {
collection.insert({ a: 1 }, (err, docs) => {
collection.find({ name: "Donald" }, (err, cursor) => {
cursor.toArray((err, items) => {
test.assertEquals(1, items.length);
// Let's close the db
p_client.close();
});
});
});
});
});
fetch("https://api.coindesk.com/v1/bpi/currentprice.json")
.then(res => res.json())
.then(res => res.bpi.USD.rate_float)
.then(rate => console.log(`Current BTC/USD Rate: ${rate}`))
.catch(err => console.error(err));
// Parallel Execution
Promise.all([
fetch("https://api.coindesk.com/v1/bpi/currentprice.json"),
fetch("https://api.coindesk.com/v1/bpi/historical/close.json")
]).then(([currentPrice, historicalPrices]) =>
console.log(currentPrice, historicalPrices)
).catch(err => console.error(err));
// Variable Passthrough
User.findOne({ name: "realDonaldTrump" })
.then(user => Promise.all([user, Tweets.find({ user_id: user.id })]))
.then(([user, tweets]) => {
console.log(`User ${user.name} has ${tweets.length} tweets`);
});
async function getBtcRate() {
try {
const res = await fetch("https://api.coindesk.com/v1/bpi/currentprice.json");
const currentPrice = await res.json();
const rate = res.bpi.USD.rate_float;
console.log(`Current BTC/USD Rate: ${rate}`)
} catch (err) {
console.error(err);
}
}
// Parallel Execution
async function getBtcData() {
try {
const [currentPrice, historicalPrices] = await Promise.all([
fetch("https://api.coindesk.com/v1/bpi/currentprice.json"),
fetch("https://api.coindesk.com/v1/bpi/historical/close.json")
])
console.log(currentPrice, historicalPrices)
} catch (err) {
console.error(err);
}
}
// Don't loose access to previous results
async function getUserTweets({ username }) {
try {
const user = await User.findOne({ name: username });
const tweets = await Tweets.find({ user_id: user.id });
console.log(`User ${user.name} has ${tweets.length} tweets`);
} catch (err) {
console.error(err);
}
}
// Mixing async/await with FP
async function getUserTweets({ users }) {
try {
const tweets = await Promise.all(
users.map(user => Tweets.find({ user_id: user.id }))
);
console.log(`A total of ${tweets.length} tweets for ${users.length} users has been returned`);
return tweets;
} catch (err) {
console.error(err);
}
}
supported by standard library
foundation for async/await
most clear and simple code