Skip to content

Instantly share code, notes, and snippets.

View patarkf's full-sized avatar

Patrick Ferreira patarkf

View GitHub Profile
async function makeRequest() {
const response = await fetch('foo');
if (response.doestItNeedAnotherRequest) {
const secondResponse = await makeAnotherRequest(response);
console.log(secondResponse);
return secondResponse;
}
console.log(response);
let promise = Promise.resolve();
const posts = [{}, {}, {}];
posts.forEach(post => {
promise = promise.then(() => {
return db.insert(post);
});
});
promise.then(() => {
posts.forEach(post => {
promise = promise.then(db.insert(post));
});
const posts = [{}, {}, {}];
async function insertPosts(posts) {
for (let post of posts) {
await db.insert(post);
}
}
const posts = [{}, {}, {}];
async function insertPosts(posts) {
posts.forEach(post => {
await db.insert(post);
});
}
const posts = [{}, {}, {}];
async function insertPosts(posts) {
posts.forEach(async post => {
const postId = await db.insert(post);
console.log(postId);
});
// Not finished here
}
const posts = [{}, {}, {}];
function insertPostsConcurrently(posts) {
return Promise.all(posts.map(doc => {
return db.insert(post);
})).then(results => {
console.log(results);
});
}
const posts = [{}, {}, {}];
async function insertPostsConcurrently(posts) {
const promises = posts.map(post => db.insert(post));
const results = await Promise.all(promises);
console.log(results);
}
async function getConcurrently() {
let promises = [];
promises.push(getUsers());
promises.push(getCategories());
promises.push(getProducts());
let [users, categories, products] = await Promise.all(promises);
}
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