Instantly share code, notes, and snippets.

View .js
async function printFiles () {
const files = await getFilePaths();
await Promise.all(files.map(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
}));
}
View .js
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)
})
}
View .js
//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
View .js
//implements Promise way
const getUserPromise = (name) => {
return getUserByName('andrew')
.then(function (user) {
if (user.role == 'guest') {
return user;
} else {
return false;
}
})
View .js
const getUser = async (name) => {
const user = await getUserByName(name);
const account = await getUserAccountById(user.id);
return account;
}
const myUser = getUser('andrew');
View .js
Promise.resolve(someSynchronousValue).then(/* ... */);
View .js
new Promise(function (resolve, reject) {
resolve(someSynchronousValue);
}).then(/* ... */);
View promiseReturn.js
getUserByName('andrew').then(function (user) {
return getUserAccountById(user.id);
}).then(function (userAccount) {
// userAccount data here
});
View rookieMistake5.js
somePromise().then(function () {
someOtherPromise();
}).then(function () {/* ... */});
View bluebirdPromise.js
// 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);
});