Skip to content

Instantly share code, notes, and snippets.

View schahriar's full-sized avatar

Schahriar SaffarShargh schahriar

  • San Francisco, United States
View GitHub Profile
@schahriar
schahriar / loop-basic-parallel.js
Last active January 14, 2018 09:48
For Loop basic parallel #async-await #medium
async (items) => {
let promises = [];
for (let i = 0; i < items.length; i++) {
promises.push(db.get(items[i]));
}
const results = await Promise.all(promises);
console.log(results);
}
@schahriar
schahriar / loop-basic.js
Created January 14, 2018 09:37
For Loop basic #async-await #medium
async (items) => {
for (let i = 0; i < items.length; i++) {
const result = await db.get(items[i]);
console.log(result);
}
}
@schahriar
schahriar / promise-that-throws.js
Last active January 14, 2018 08:37
Promise that throws #async-await #medium
const PromiseThatThrows = (message) => new Promise((resolve, reject) => {
// Reject after 100ms with a new error
setTimeout(() => reject(new Error(message))), 100);
};
@schahriar
schahriar / error-handling-2.js
Last active January 14, 2018 08:40
Try/Catch block complex #async-await #medium
const throwsLater = async () => {
await PromiseThatThrows('Some error');
};
async () => {
try {
// Note that without await
// the error will never be
// caught
await throwsLater;
@schahriar
schahriar / promisifying.js
Created January 14, 2018 00:27
Util#promisify #async-await #medium
const fs = require('fs');
const { promisify } = require('util');
// Function#bind as needed
const readFile = promisify(fs.readFile);
const writeFile = promisify(fs.writeFile);
const transform = () => /* ... */;
const transformFileAsync = async (source, dest) => {
@schahriar
schahriar / basic.js
Last active January 13, 2018 23:50
[The Basics] Basic usage of async/await #async-await #medium
const getUser = async (query) => {
const user = await Users.findOne(query);
const feed = await Feeds.findOne({ user: user._id });
return { user, feed };
};
// getUser will return a promise
getUser({ username: 'test' }).then(...);