Skip to content

Instantly share code, notes, and snippets.

View pionize's full-sized avatar

Andrew Junior Ongi Karyanto pionize

View GitHub Profile
async function printFiles () {
const files = await getFilePaths();
await Promise.all(files.map(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
}));
}
import fs from 'fs-promise'
async function printFiles () {
const files = await getFilePaths() // Assume this works fine
files.forEach(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
})
}
//implements Promise
const getAllUsers = () => {
try {
getUsers()
.then(result => {
// this parse may fail
const data = JSON.parse(result)
console.log(data)
})
// uncomment this block to handle asynchronous errors
@pionize
pionize / .js
Created July 25, 2017 02:04
conditional if, promise vs async/await
//implements Promise way
const getUserPromise = (name) => {
return getUserByName('andrew')
.then(function (user) {
if (user.role == 'guest') {
return user;
} else {
return false;
}
})
@pionize
pionize / .js
Created July 25, 2017 01:38
Async/Await
const getUser = async (name) => {
const user = await getUserByName(name);
const account = await getUserAccountById(user.id);
return account;
}
const myUser = getUser('andrew');
Promise.resolve(someSynchronousValue).then(/* ... */);
new Promise(function (resolve, reject) {
resolve(someSynchronousValue);
}).then(/* ... */);
getUserByName('andrew').then(function (user) {
return getUserAccountById(user.id);
}).then(function (userAccount) {
// userAccount data here
});
@pionize
pionize / rookieMistake5.js
Created April 17, 2017 10:12
Promise without return
somePromise().then(function () {
someOtherPromise();
}).then(function () {/* ... */});
@pionize
pionize / bluebirdPromise.js
Created April 17, 2017 10:10
Bluebird Promise
// using Bluebird Promise
const Promise = require('bluebird');
new Promise(function (resolve, reject) {
fs.readFile('myfile.txt', function (err, file) {
if (err) {
return reject(err);
}
resolve(file);
});