Skip to content

Instantly share code, notes, and snippets.

View patarkf's full-sized avatar

Patrick Ferreira patarkf

View GitHub Profile
/**
* Always waits one second, then "toss a coin", having
* a 50/50 chance to get either true or false. Throws
* an error if false.
*/
async function waitAndMaybeReject() {
await new Promise(r => setTimeout(r, 1000));
const isHeads = Boolean(Math.round(Math.random()));
const assert = require('assert');
test('Testing async code', async () => {
const first = await getAsyncResult();
assert.strictEqual(first, 'foo');
const second = await getAsyncResult2();
assert.strictEqual(second, 'bar');
});
const assert = require('assert');
test('Testing async code', () => {
getAsyncResult() // A
.then(first => {
assert.strictEqual(first, 'foo'); // B
return getAsyncResult2();
})
.then(second => {
assert.strictEqual(second, 'bar'); // C
async function getConcurrently() {
let promises = [];
promises.push(getUsers());
promises.push(getCategories());
promises.push(getProducts());
let [users, categories, products] = await Promise.all(promises);
}
const posts = [{}, {}, {}];
async function insertPostsConcurrently(posts) {
const promises = posts.map(post => db.insert(post));
const results = await Promise.all(promises);
console.log(results);
}
const posts = [{}, {}, {}];
function insertPostsConcurrently(posts) {
return Promise.all(posts.map(doc => {
return db.insert(post);
})).then(results => {
console.log(results);
});
}
const posts = [{}, {}, {}];
async function insertPosts(posts) {
posts.forEach(async post => {
const postId = await db.insert(post);
console.log(postId);
});
// Not finished here
}
const posts = [{}, {}, {}];
async function insertPosts(posts) {
posts.forEach(post => {
await db.insert(post);
});
}
const posts = [{}, {}, {}];
async function insertPosts(posts) {
for (let post of posts) {
await db.insert(post);
}
}